【发布时间】:2020-03-12 04:24:17
【问题描述】:
我在后端使用 Axios 时遇到问题。这可能是一个非常简单的修复,因为我是新手。
邮递员:收到有效和无效凭据的正确响应。
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 catch 块运行,所以我没有收到 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));
}
控制台中的无效凭据错误: 单击突出显示的链接会打开一个新页面,说明:“无法获取 /auth/login”,但我显然正在发出帖子请求,并且我已将帖子添加到表单中(以防万一)
有什么我可能会遗漏的想法吗?
谢谢
【问题讨论】:
标签: javascript node.js axios