[英]Error using Axios, but correct response in Postman
我在后端使用 Axios 时遇到问题。 这可能是一个非常简单的修复,因为我是新手。
Postman:收到有效和无效凭证的正确响应。
Axios:接收到有效凭证的正确响应,但在输入无效凭证时运行 axios 方法的 catch 块。
authController.js:
exports.login = (req, res, next) => {
const email = req.body.email;
const pass = req.body.password;
let loadedUser;
User.findOne({ where: { email: email } })
.then(user => {
if(!user) {
const error = new Error('Incorrect username or password');
error.statusCode = 401;
throw error;
} else {
loadedUser = user;
return bcrypt.compare(pass, user.password);
}
})
.then(isEqual => {
if(!isEqual) {
const error = new Error('Incorrect username or password');
error.statusCode = 401;
throw error;
} else {
const token = jwt.sign(
{
email: loadedUser.email,
userId: loadedUser.id
},
process.env.JWT_SECRET,
{ expiresIn: '1hr' }
);
res.status(200).json({ token: token, userId: loadedUser.id });
}
})
.catch(err => {
if (!err.statusCode)
err.statusCode = 500;
next(err);
});
};
app.js 中的错误处理程序。 输入不正确的凭据时,似乎可以正确记录错误,即使使用 axios:
app.use((error, req, res, next) => {
const status = error.statusCode || 500;
const message = error.message;
const data = error.data || 'No Data';
console.log(status, message, data);
res.status(status).json({message: message, data: data});
});
但是随后 axios 捕获块运行,因此我收到以下错误消息,而不是收到 json 消息
login(email, password) {
const headers = {
'Content-Type': 'application/json'
};
const data = JSON.stringify({
email: email,
password: password
});
axios.post('http://127.0.0.1:8080/auth/login', data, { headers })
.then(res => console.log(res))
.catch(err => console.log(err));
}
无效凭据的控制台错误: 单击突出显示的链接会打开一个新页面,说明:“Cannot GET /auth/login”,但我显然是在发出帖子请求,并且我已经在表单中添加了帖子(以防万一)
有什么想法我可能会错过吗?
谢谢
实际上,您的代码工作正常,但如果您的状态为401 ,Axios 将拒绝呼叫的 promise 。 如果您的状态介于 200 到 300 之间,它将解决 promise。
有两种方法可以解决这个问题。
检查 catch 块中的状态。
axios.post('http://127.0.0.1:8080/auth/login', data, {
headers
})
.then(res => console.log(res))
.catch(err => {
if (err.response.status === 401) {
//Auth failed
//Call reentry function
return;
}
return console.log(err)
});
或更改validateStatus
选项;
axios.post('http://127.0.0.1:8080/auth/login', data, {
headers,
validateStatus: function (status) {
return status >= 200 && status < 300 || (status === 401);
},
})
.then(res => console.log(res))
.catch(err => return console.log(err));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.