Javascript 在Promise中的first-then()之后访问和使用响应状态代码时出现问题
正如标题中所述,我试图使用响应状态代码,该代码在第一个Javascript 在Promise中的first-then()之后访问和使用响应状态代码时出现问题,javascript,reactjs,express,es6-promise,Javascript,Reactjs,Express,Es6 Promise,正如标题中所述,我试图使用响应状态代码,该代码在第一个中可用,然后与JSON响应数据一起使用,但在promise的稍后阶段。但是却得到了SyntaxError:JSON中位置0处的意外标记U 承诺片段: //fetch request .then((res) => //can access status code here res.json().then((data) => ({ status: res.status, sid: data.sid }))
中可用,然后与JSON响应数据一起使用,但在promise的稍后阶段。但是却得到了SyntaxError:JSON中位置0处的意外标记U
承诺片段:
//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));
if (user) {
req.session.userID = user._id;
res.status(200).json({ sid: req.session.id });
} else {
res.sendStatus(401);
}
}
快速路线片段:
//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));
if (user) {
req.session.userID = user._id;
res.status(200).json({ sid: req.session.id });
} else {
res.sendStatus(401);
}
}
您的承诺链接逻辑不正确,因为它没有从first then block返回承诺
试着像这样把它拴起来-
//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));
您的承诺链接逻辑不正确,因为它没有从first then block返回承诺
试着像这样把它拴起来-
//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));
您的承诺链接逻辑不正确。该错误表示您从中获取的资源未返回JSON。您的承诺链接逻辑不正确。该错误表示您从中获取的资源未返回JSON。