我正在尝试通过 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 应用程序的服务器端打印出密钥,但我什么也没得到,是空的。 (这是预期的,因为 POST 请求失败)
dict = request.form
for key in dict:
print('form key '+dict[key])
但是,将 Postman 与相应的键和值一起使用可以正常工作并返回响应并打印出键(见上文)。失败从何而来?为什么 GET 看起来工作正常时 POST 请求会失败?
原文由 M Xiao 发布,翻译遵循 CC BY-SA 4.0 许可协议
2021 年 2 月。为此浪费了 2 个小时。对这个著名的互联网图书馆帮助不大。
解决方案:
error
永远是500 internal server error
error.response.data
而不是error
。代码:
更新:
我最终编写了一个处理错误的通用函数:
文件:common.app.js
更多信息: https ://github.com/axios/axios#handling-errors