javascript - 使用 Axios 时出错,但 Postman 中的响应正确
问题描述
我在后端使用 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”,但我显然正在发出发布请求,并且我已将帖子添加到表单中(就在案子)
有什么想法我可能会错过吗?
谢谢
解决方案
Actually your code works fine but Axios will reject the promise of the call if you have the status 401. If you have a status between 200 to 300 it will resolve the promise.
There two ways to deal with this.
Check status in the catch block.
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)
});
or change the validateStatus
option;
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));
推荐阅读
- jquery - 空格的codeigniter表单验证正则表达式不起作用
- reactjs - React 挂钩更新状态未传递给函数
- java - 使用 -Xlint 重新编译:制作 ArrayList 时未选中详细信息
- php - 以一种形式更新多个 MYSQL 列
- export - mysql工作台导出sql文件而不是sql文本文件
- javascript - 如何在 React 中更改组件导航的标题文本?
- c++ - 当我在 C++ 中使用 Node(key,data) 而不是 Node.key 和 Node.data 时,单链表不起作用
- ssis - SSIS 包 FLAT 文件加载到 SQL 表并转换数据以截断试用空间,将字符串转换为日期时间
- jquery - jQuery UI 日期选择器查询
- javascript - 检查对象数组中的字符串