javascript - 如何从 ReactJS 中的 400 http 响应中获取响应数据
问题描述
我已经在后端设置了快递,如果帐户已经存在,这就是逻辑。
try {
//check if email already exists
const existingUser = await User.findOne({ email : email });
if (existingUser) {
// return res.send('Already exists')
return res.status(400).json({err: "Account with email already exists"});
};
我能够使用 axios 为 200/201... 响应获取数据。但不是为了这个。IT 还将 json 响应返回给 POSTMAN,但不返回 400 代码的 axios。我需要提取 我的前端代码的响应数据!
const submit = async (e) => {
e.preventDefault();
if(password !== password2){
setErr("Passwords do not match")
};
const userData = { name, email, password };
const url = "http://localhost:5000/api/users/signup";
const res = await axios.post(url, userData);
// NO OUTPUT
console.log(res.data);
console.log(res);
}
解决方案
你需要一个try / catch
const submit = async e => {
e.preventDefault();
if (password !== password2) {
setErr("Passwords do not match");
}
const userData = { name, email, password };
const url = "http://localhost:5000/api/users/signup";
try {
const res = await axios.post(url, userData);
} catch (err) {
console.log(err.response);
}
};
推荐阅读
- php - 使用 PHP 以 CSV 文件格式下载
- node.js - multer req.body 总是显示为空
- git - 将主分支与开发同步
- visual-studio - ASP.NET Core 启动设置:IIS Express、IIS、项目、可执行文件
- android - 饼图显示剪切窗口属性更改未反映在使 videoview 全屏
- python - 计算模式同时忽略某些值
- apache - 使用 .htaccess 删除 URl 的某些部分?
- xamarin - 无法将类型“System.Windows.Input.ICommand”隐式转换为“Xamarin.Forms.Command”
- linux - dotnet restore 在配置有代理的 bitbucket 管道上失败
- c# - 在 Unity 中为我的 3d 模型添加动画?