Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.7k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...