express - 为什么我的 Post 请求没有返回正确的错误?
问题描述
我创建了一个服务器端请求来处理登录。该请求在邮递员中正常工作。如果我将正确的登录数据传递给它,它也可以在客户端正常工作。但是,当我尝试使用不正确的数据(例如不正确的电子邮件或密码)在客户端发出请求时,它只会返回 401 错误,而应该返回“电子邮件登录失败”或“登录失败”的消息密码失败”。但是我可以在邮递员中使用相同的错误数据提出相同的请求,它会返回正确的结果。
服务器端
router.post("/login", async (req, res) => {
let getUser;
// finds user via email
await User.findOne({
email: req.body.email,
})
.then((user) => {
if (!user) {
return res.status(401).json({
message: "Login Failed at email",
});
}
getUser = user;
return bcrypt.compare(req.body.password, user.password);
})
.then((response) => {
if (!response) {
return res.status(401).json({
message: "Login Failed at password",
});
}
})
.then(() => {
let jwToken = jwt.sign(
{
email: getUser.email,
userId: getUser.id,
},
"longer-secret-is-better",
{
expiresIn: "2h",
}
);
res.status(200).json({
token: jwToken,
expiresIn: 600,
user: getUser,
});
})
.catch((err) => {
return res.status(401).json({
message: err.message,
});
});
});
客户端请求
import axios from "axios";
export const login = (userInfo) => async (dispatch) => {
dispatch({
type: "SET_INFO_REQUEST",
});
try {
await axios({
method: "post",
url: "https://ecommersappbytim.herokuapp.com/auth/login",
header: { "Content-Type": "application/json" },
data: {
email: userInfo.email,
password: userInfo.password,
},
}).then((response) => {
console.log(response.data);
dispatch({
type: "SET_INFO_SUCCESS",
payload: response.data.user,
});
});
} catch (error) {
dispatch({
type: "SET_INFO_FAILURE",
error,
});
}
};
所以我唯一的问题是当使用 axios 在客户端传递不正确的登录数据时,它并没有给我我期望的回报
解决方案
推荐阅读
- vb.net - 构建错误:“文件具有无效值...”
- hyperledger-fabric - IBM Blockchain v2 上的 getState():加载时间过长
- r - 如何选择所有列以及附加表达式
- asp.net-mvc - HTML Actionlink 中的 ASP Route Data 属性
- ios - viewForSupplementaryElementOfKind 没有被调用
- swift - 将结构数组中的 UIColor 保存到 UserDefaults
- html - 页面没有响应 Div 标签
- angular-material - Angular Material:为什么 mat-form 没有将 mat-hint 包裹在里面?
- python - 递归函数下只在if语句中返回
- vba - 从字符串中间删除零