发生了什么事
我的项目有一个名为/login
的路由,当用户尝试登录并且他不是“ MANAGER”(数据库的属性)时,应该给出401错误。在后端,它可以正常工作,但是前端提取时未收到error
,我不知道为什么。
我的代码Node.js:
const {
findByMail
} = require('../data/acl/acl.model');
module.exports =
async function isAuthenticated(req, res, next) {
const acl = await findByMail(req.body.username);
if (acl && acl.role !== "MANAGER") {
res.status(401).send("You dont have access")
}
next()
}
我的前端:
handleLogin = async() => {
try {
this.setState({
loading: true
});
const rawResponse = await fetch('/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ ...this.state
}),
});
const response = await rawResponse.json();
localStorage.setItem('user-token', response.token);
this.setState({
loading: false
});
} catch (err) {
this.setState({
loading: false
});
console.log(err);
}
};
Console.log:
SyntaxError: Unexpected token F in JSON at position 0
at Login._callee$ (login.js:18)
at tryCatch (runtime.js:62)
at Generator.invoke [as _invoke] (runtime.js:296)
at Generator.prototype.(anonymous function) [as next] (https://localhost:3000/static/js/bundle.js:103406:21)
at step (background.login.png:1)
at background.login.png:1
login.js:18 POST https://localhost:3000/login 401 ()
我不知道怎么了,有人可以帮我吗?
答案 0 :(得分:1)
问题很简单,fetch()不会将401代码识别为不可接受的响应,因此不会调用您的catch,而是将继续执行类似200代码的代码。
收到回复后,您应该执行以下操作:
handleLogin = async() => {
try {
this.setState({
loading: true
});
const rawResponse = await fetch('/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ ...this.state
}),
});
if(!rawResponse.ok){
this.setState({
loading: false
});
}
else{
const response = await rawResponse.json();
localStorage.setItem('user-token', response.token);
this.setState({
loading: false
});
}
} catch (err) {
this.setState({
loading: false
});
console.log(err);
}
};