gpt4 book ai didi

javascript - Axios POST 请求失败,错误状态代码 500 : Internal Server error

转载 作者:数据小太阳 更新时间:2023-10-29 04:16:35 27 4
gpt4 key购买 nike

我正在尝试通过 Axios 在本地发送一个带有用户名和密码的 POST 请求。

我正在 http://127.0.0.1:5000/login 上部署 Flask 应用程序,它处理/login 路由。 POST 请求失败,出现以下错误

POST http://127.0.0.1:5000/login 500 (INTERNAL SERVER ERROR)
Error: Request failed with status code 500
at createError (createError.js:16)
at settle (settle.js:18)
at XMLHttpRequest.handleLoad (xhr.js:77)

我研究了一下,认为这可能是 CORS 的问题,但事实似乎并非如此,因为我尝试了 Axios GET 请求并且它工作正常(正确记录了响应)。这是我的部分代码

axios.get("http://127.0.0.1:5000").then(function(response) {
console.log(response);
}).catch(function(error) {
console.log(error);
})
axios.post("http://127.0.0.1:5000/login", {
username: this.state.username,
password: this.state.password
}).then(function(response) {
console.log(response);
}).catch(function(error) {
console.log(error);
})

查看 Chrome DevTools,我可以看到 POST 请求负载已正确填充。然后我尝试使用以下代码在 Flask 应用程序的服务器端打印出 key ,但我什么也没得到,是空的。 (这是预期的,因为 POST 请求失败)

dict = request.form
for key in dict:
print('form key '+dict[key])

但是使用具有相应键和值的 Postman 可以正常工作并返回响应并打印出键(见上文)。失败从何而来?为什么 GET 看起来工作正常时 POST 请求会失败?

最佳答案

2021 年 2 月。为此浪费了 2 个小时。对互联网上这个著名的图书馆帮助不大。

解决方案:

  • 在 catch block 中,error 始终是 500 internal server error
  • 因此,使用 error.response.data 而不是 error

代码:

try {
let result = await axios.post( // any call like get
"http://localhost:3001/user", // your URL
{ // data if post, put
some: "data",
}
);
console.log(result.response.data);
} catch (error) {
console.error(error.response.data); // NOTE - use "error.response.data` (not "error")
}

更新:

我最终写了一个处理错误的通用函数:

文件:common.app.js

export const errorUtils = {
getError: (error) => {
let e = error;
if (error.response) {
e = error.response.data; // data, status, headers
if (error.response.data && error.response.data.error) {
e = error.response.data.error; // my app specific keys override
}
} else if (error.message) {
e = error.message;
} else {
e = "Unknown error occured";
}
return e;
},
};

更多信息:https://github.com/axios/axios#handling-errors

关于javascript - Axios POST 请求失败,错误状态代码 500 : Internal Server error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50950011/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com