【问题标题】:express redirect got response 304 and do nothing快速重定向得到响应 304 并且什么也不做
【发布时间】:2021-08-01 21:26:38
【问题描述】:

前端是响应并请求服务器使用 Fetch 。

这样的代码。

        fetch(`/ONETOWN/LARK/PACKAGE/STOCKOUT/LOAD_LIST_BY_TELL`,{
        method: "POST",
        headers: {
          "Accept": "application/json",
          "Content-Type": "application/json",
        },
        credentials: 'include',
        body: JSON.stringify(info)
      })

这样的后端(服务器)代码,cookie过期,所以我希望重定向到未经授权的页面。

    static authentication(req,res) {
    if(this.verifyCookie(req,res)) {
        return true;
    }   
    //res.status(401).end();

    res.redirect('/#/page/unauthorized');

    return false;
} 

my Web don't redirect to the path i want,still stay the original page

如果重定向更改为位置方法 res.location('/#/page/unauthorized').end()

得到响应 200

got response 200

【问题讨论】:

    标签: node.js reactjs express fetch-api


    【解决方案1】:

    问题是您正在使用fetch 调用进行 HTTP 调用,因此您的浏览器没有发出请求,因此它不知道需要打开不同的页面。

    解决方案是检查您的fetch 呼叫的响应,并在需要时重定向到不同的页面。

    【讨论】:

      【解决方案2】:

      感谢@Ayzrian,我已经更改了我的代码逻辑来解决这个问题。你是对的,我应该在前端做重定向,检查服务器响应的状态(401),这样的代码。

      enter code here
      fetch(`url`,{
           method: "POST",
              headers: {
                "Accept": "application/json",
                "Content-Type": "application/json",
              },
              credentials: 'include',
              body: JSON.stringify(info)
            })
          .then(res => Authentication(res))
          .then(res => res.json())
          .then(json => {
      
          }).catch((e) => {
              if (e.status === 401) {
                  console.log(e);
                  window.location="#/page/unauthorized";
              }
          });
      };
      

      .......................

          export const Authentication  = (res) => {
        if (res.ok) {
            return res;
        } else {
            return Promise.reject({
              status: res.status,
              statusText: res.statusText
            });
        }
      }
      

      .......

      static authentication(req,res) {
          if(this.verifyCookie(req,res)) {
              return true;
          }   
          res.status(401).end();
          //res.redirect('/#/page/unauthorized');  not works 
      
          return false;
      }
      

      【讨论】:

        猜你喜欢
        • 2015-02-16
        • 2010-09-22
        • 1970-01-01
        • 1970-01-01
        • 2020-07-29
        • 2014-07-02
        • 1970-01-01
        • 1970-01-01
        • 2020-04-03
        相关资源
        最近更新 更多