Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k 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 Reply

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...