我正在尝试通过 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 请求会失败?
2021 年 2 月。为此浪费了 2 个小时。互联网上这个著名的图书馆没有太多帮助。
解决方案:
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;
},
};
所以我也陷入了同样的问题,我找到的解决方案是这样的:
let data = JSON.stringify({
username: this.state.username,
password: password
});
const response = axios.post(url,data,{headers:{"Content-Type" : "application/json"}});
这个解决方案对我有用。
显然 Axios 对原始 JSON 对象并不友好
{username: this.state.username, password: password}
但是将数据传递到 FormData 对象似乎工作得很好!
工作了2个小时后,我意识到我在body和数据上犯了一个错误。因此,在 axios 中请确保像这样传递数据。
async function loadToken(){
try{
response = await axios({
url: ``,
headers: {
'Authorization': '',
'Content-Type': '',
},
data: '',
method: 'POST'
});
let data = response.data;
return {
tokenInfo:data,
timestamp:new Date().getTime()
}
} catch(err) {
console.log("err->", err.response.data)
return res.status(500).send({ret_code: ReturnCodes.SOMETHING_WENT_WRONG});
}
}
我之前的代码是这样传递数据的,这是错误的
async function refreshToken(){
try{
let headers = {
authorization: '',
'Content-Type': ''
}
let url = ``
let body = {
grant_type: '',
refresh_token: global.tokenInfo.refresh_token
}
data = await axios.post(url, body, {headers});
let data = response.data
console.log(data)
return {
tokenInfo:data,
timestamp:new Date().getTime()
}
} catch(err) {
console.log("err->", err.response)
return res.status(500).send({ret_code: ReturnCodes.SOMETHING_WENT_WRONG});
}
}
只需尝试我的第一个代码,希望能解决您的问题。
大多数时候发生这种情况是因为使用了错误的内容类型标题。
打开邮递员并查看“正文”选项卡。在那里您可以找到帖子数据的内容类型。也可以从“标题”选项卡访问它。应该有一个
Content-Type
标题。通过 POST 请求发送的 data
的正确格式取决于 Content-Type
标头。例如,json 内容类型需要 json(javascript 对象)数据或 form-data 内容类型需要 FormData。
要在 axios 中设置标头,请像这样更改代码:
axios.post("http://127.0.0.1:5000/login", {
username: this.state.username,
password: this.state.password
}, {
headers: {'Content-Type': 'application/json'}
}).then(function(response) {
console.log(response);
}).catch(function(error) {
console.log(error);
})
我有类似的错误,我有 JSON 大写,它应该是小写
使用body-parser(服务器节点js)