reactjs - 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"));
解决方案
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);
});
推荐阅读
- python - 应用循环中的 Python 多处理 pool.map 导致重置和奇怪的行为
- ruby-on-rails - 如何在两个 Mutation 类之间共享参数
- javascript - 如何在没有框架的情况下将数据插入 HTML/JavaScript 中的模板元素
- html - 字体从 http 变为 https
- material-ui - React Styleguidist 包装器 - 模块解析失败:意外令牌
- javascript - 模拟 window.navigator 对象
- python - 有什么办法可以优化逻辑回归模型的代码
- json - 警告:列表中的每个孩子都应该有一个唯一的“key”道具,即使有一个键?
- excel - 在 VBA 中模拟 M 几何布朗运动路径
- excel - 删除 || (管道)在列内文本的末尾