Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
983 views
in Technique[技术] by (71.8m points)

javascript - Problems accessing and using response status code after first then() in Promise

As outlined in the title, i'm trying to use the response status code which is available in the first then alongside the JSON response data, but at a later stage in the promise. But instead getting SyntaxError: Unexpected token U in JSON at position 0

promise snippet:

 //fetch request
 .then((res) =>
      //can access status code here
      res.json().then((data) => ({ status: res.status, sid: data.sid }))
    )
    .then((data) => {
      // status code undefined 
      if (data.status === 401) {
        setShowError(true);
        setErrorMessage("Your email and/or password is incorrect.");
      } else if (data.status === 200) {
        localStorage.setItem("_sid", data.sid);
        history.push("/");
      }
    })
    .catch((err) => console.log(err));

express route snippet:

if (user) {
        req.session.userID = user._id;
        res.status(200).json({ sid: req.session.id });
      } else {
        res.sendStatus(401);
      }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your promise chaining logic is incorrect as it is not returning a promise from first then block.

Try chaining it like this -

//fetch request
 .then((res) => res.json())
 .then((data) => ({ status: res.status, sid: data.sid }))
 .then((data) => {
      // status code undefined 
      if (data.status === 401) {
        setShowError(true);
        setErrorMessage("Your email and/or password is incorrect.");
      } else if (data.status === 200) {
        localStorage.setItem("_sid", data.sid);
        history.push("/");
      }
    })
    .catch((err) => console.log(err));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...