首页 > 解决方案 > 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,但我仍然不明白为什么重定向不起作用。那我每次都要手动设置吗?

标签: node.jsreactjsexpressreact-routerfetch

解决方案


推荐阅读