首页 > 解决方案 > 响应 fetch API 请求区分重定向/JSON 数据

问题描述

我正在尝试在前端构建一个逻辑来区分重定向和 JSON 响应,最终目标是,如果响应是重定向到该页面,并且如果响应有数据,那么它将呈现该数据这页纸。

注意:如果后端以 res.redirect 或 res.json 的形式发送响应,它工作正常,但我正在努力(如下面的代码),因为当我必须首先检查来自后端的响应是什么时,我想好像我可以在前端使用 if else 语句在 res.json 和 res.respond 之间进行恶心,我尝试过类似 .then(res.redirect=>{...}).then(res.json=>{}) 但是如果我使用正确的逻辑,它看起来不像。请有任何建议,谢谢:slightly_smiling_face:

我的前端代码片段是 .

const request = new Request("http://localhost:5000/api/newuser", options);

    (async () => {

      const incomingdata = await fetch(request)

 *// below i  differetiated the incoming response as if it is res.redirect or res.json data but didnt work*
        .then((res.redirect) => {                  

          window.location.href = res.url;

        })
         .then((res.json) => {

            console.log("cannot find data");

          })

        .catch((err) => console.log("err"));

我的银行结束代码的片段是,

connection.query("SELECT * FROM  users WHERE email=?;", [x1.Email], function (

    err,

    results

  ) {

    console.log("74",results, err);

    console.log("75",results[0].email);

    if (err) throw err;

    else {

      if (results[0].email && results[0].password) {

        console.log("79",results[0].email);

        //console.log(results[0]);

        if (results[0].password == x1.password)

          res.redirect("http://localhost:3000/");

        else {

          res.json({

            data: "invalid password",

          });

        }

      } else res.redirect("http://localhost:3000/about");

    }

  });

});

标签: javascriptnode.jsreactjs

解决方案


对于重定向,您可以检查 HTTP 代码是否在 res.status 中提供的 300 范围内。它不需要点符号,所以,你可以使用

.then(res => {
  if(res.status >= 300 && res.status < 400){
    // redirect
  } else {
    return res.json();
  }
})
.then(data => {
  //handle your json data
});

在回调参数中使用点将是语法错误,例如: .then((res.json) => {

但是,可以像这样解构对象: .then(({ status, json }) => {


推荐阅读