node.js - Fetch/React 不使用 Node/Express res.redirect() 重定向
问题描述
在我的 React 前端,我对我的 Node/Express 服务器进行了 fetch() GET 调用。Node/Express 服务器检查响应是否有特定的 cookie,如果没有则重定向它。我的代码是这样的:
反应代码
componentDidMount(){
fetch('/example',{redirect: "follow"})
.then(data => data.json())
.then(res => {
//do something with response
}
})
}
节点/快递:
router.use((req, res, next) => {
let { token } = req.cookies;
if(token){
next();
}
else{
res.redirect(303, '/login');
}
});
router.get('/example', (req, res) =>{
//sends a json response back
})
重要的是要注意我使用 react-router-dom 作为浏览器路由器,我想我不确定这对服务器重定向有什么作用。我搜索并看到有人说将重定向设置为“关注”。但是,即使将状态设置为 3xx 并将重定向设置为“关注”,页面仍然无法正确重定向。相反,它会收到一个响应200 OK status
(我不明白它是如何改变的,除非 Node/Express 实际上没有将它设置为'303'),redirected: true
,以及一个指向重定向 url 的 response.url,但仍停留在同一页面上。我已经确定 cookie 不存在,所以不是这样。我知道我可能每次都可以检查 response.redirected 并手动设置 window.location = response.url,但我仍然不明白为什么重定向不起作用。那我每次都要手动设置吗?
解决方案
推荐阅读
- python - 挂载作业输出数据作为 Floydhub 中另一个作业的输入数据
- python-3.x - 在散景渲染后是否可以将边缘/节点信息返回给 python?
- c++ - 如何找出字符串是否只有数字,没有字母
- c# - 有没有办法在 WebAPI 中不引用 EntityFramework?
- angular - 到前一个组件的角度路由不起作用
- cpu - 操作系统中的上下文切换
- bixby - 如何让 bixby 使用 app-launch 打开谷歌地图?
- react-native - 有没有办法在 Firebird 数据库和 React-Native 应用程序之间建立连接?
- java - Java EE 7 - 如何从容器内部启动事务?
- python-3.x - 我的卷积网络损失没有改变,并且在整个训练过程中保持停滞。如何解决这个问题?