Prevent React Router from routing a server API path

[亡魂溺海] 提交于 2021-02-07 06:56:18

问题


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')

回答1:


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>
      )
   }
}



回答2:


Hi i had the same issue and this was my solution, this is my DefaultController the entry point of the React app.

class DefaultController extends AbstractController
{
   /**
   * @Route("/{reactRouting}", name="home", requirements={"reactRouting"="^(?!api).+"}, defaults={"reactRouting": null})
   */
  public function index()
  {
    return $this->render('default/index.html.twig', [
        'controller_name' => 'DefaultController',
    ]);
  }
}

Notice that the "requirements" defines the regex for bypass /api path, and with this react router will ignore this route and the request will be handle by the server. I hope this works for you. Regards!



来源:https://stackoverflow.com/questions/38062265/prevent-react-router-from-routing-a-server-api-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!