On the server an API only path has been set under /api
.
When calling this path on the client-side, react-router takes over and responds with:
browser.js:49 Warning: [react-router] Location "/api/my_request" did not match any routes
How can we tell react-router to bypass this and just send the request out to the server?
Update:
This is how the request is being sent:
const sock = new SockJS('http://localhost:3030/api')
sock.onopen = () => {
console.log('open')
}
sock.onmessage = (e) => {
console.log('message', e.data)
}
sock.onclose = () => {
console.log('close')
}
sock.send('test')
To restrict access to routes in React Router, we set the render prop to a function that renders the component we want according to the condition we're checking. import { Route, Redirect } from "react-router"; <Route exact path="/" render={() => (loggedIn ?
Restricting Links We add useState() to store our Link component in. Add useEffect() hook to listen to [props. user] changes (login/logout). Add a switch case to check against the condition we pass down.
Use the Navigate element to set a default route with redirect in React Router, e.g. <Route path="/" element={<Navigate to="/dashboard" />} /> . The Navigate element changes the current location when it is rendered.
To disable a Link if it's active in React Router, we set the to path of the Link 's pointer-events CSS property to none . to add the disabled-link class to the Link . to disable the mouse pointer we usually see over a link with pointer-events with none .
Here is how I bypass React Router for my API routes with React Router 4.
I had to remember that React Router is in a React component. We can use JavaScript within it and we can test the URL.
In this case, I check for /api/
in the pathname of the URL. If it exists, then I do nothing and skip React Router entirely. Else, it has a route that does not begin with /api/
and I let React Router handle it.
Here is my App.js file in my client folder:
import React from 'react'
import Home from './components/Home'
import AnotherComponent from './components/AnotherComponent'
import FourOhFour from './components/FourOhFour'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
export default function App() {
const api_regex = /^\/api\/.*/
// if using "/api/" in the pathname, don't use React Router
if (api_regex.test(window.location.pathname)) {
return <div /> // must return at least an empty div
} else {
// use React Router
return (
<Router>
<div className="App">
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/another-link" component={AnotherComponent} />
<Route component={FourOhFour} />
</Switch>
</div>
</Router>
)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With