首页 > 解决方案 > React Router 不会拦截 HTTP/S 请求

问题描述

我对 React Router 的理解是,一旦在客户端引导了单个页面,所有后续对路由的调用都不会转到服务器。它们被 React Router 拦截。但是为什么我的应用总是向服务器发出 HTTP 请求呢?尽管有 React Router 代码?当我在浏览器开发工具上看到 Networks 时,我总是看到每个“react routed”路由都有一个网络请求。

我首先启动服务器,然后传递索引文件,然后在客户端渲染完成后停止服务器来测试应用程序。然后我尝试从客户端应用程序访问另一条路由,例如“/contactus”,但请求似乎转到了服务器(现在没有运行),因此客户端没有得到任何文件并且浏览器变为空白。我的理解是,一旦应用程序的客户端引导完成,React Router 就会拦截所有 API 调用。

然后我通过执行 app.get("/*", function (req, res) { res.sendFile(path.join(__dirname, "../dist", "landing_page.html")) 修改了我的服务器端代码; });

现在该应用程序可以工作了。但这违背了 React Router 的全部目的,因为所有请求都发送到服务器。那么什么是 React Router 呢?是只做路由不做拦截吗?是否有拦截请求的 React Router 变体?还是我使用类似历史 API 的东西?这是我的代码。

import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
 
} from "react-router-dom";

class App extends React.Component {


  render() {
      return (
      <Router>
            <Switch>
            <Route exact path="/">
              <div className="banner">
                <Banner />
              </div>
            </Route>
          </Switch>
          <Switch>
            <Route exact path="/cloudautomation">
              <div style={{ position: "absolute", top: "15%", zIndex: "-1" }}>
                <CloudAutomation />
              </div>
            </Route>
          </Switch>
          <Switch>
            <Route exact path="/marketingautomation">
              <div style={{ position: "absolute", top: "15%", zIndex: "-1" }}>
                <MarketingAutomation />
              </div>
            </Route>
          </Switch>
          <Switch>
            <Route exact path="/contactus">
              <div style={{ width: "100%" }}>
                <ContactUs />
              </div>
            </Route>
          </Switch>
        </div>
        </Router>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("main"));

标签: reactjsreact-router

解决方案


React-router-dom 通常用于防止您的页面在通过您自己的网站进行路由时重新加载每个资产,从而提供 SPA 体验。

如果你想拦截请求,你可以使用axios

他们自己的文档中的示例:

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });

推荐阅读