问题描述
通过 insomnia/postman 作品发出帖子请求,给了我正确的回应。但是,在 axios 中,我似乎无法使其工作。
它没有给我一个错误,它的状态是 200,但实际上并没有像邮递员/失眠那样登录。我觉得我的 axios 设置有问题
const { email,password } = req.body.params
const endpoint = `https://xxxxxxxxx.com/account/login/`
try {
const response = await axios({
method: 'post',url: endpoint,data: qs.stringify({
'customer[email]': email,'customer[password]': password,'form_type': 'customer_login'
}),headers: {
'content-type': 'application/x-www-form-urlencoded'
}
})
res.status(200).send(response.data)
} catch (error) {
res.status(500).send(error)
}
解决方法
有两种解决方案(我希望):
1/ 在 this post 之后,您可能应该像这样使用 withCredentials
:
const { email,password } = req.body.params
const endpoint = `https://xxxxxxxxx.com/account/login/`
axios.defaults.withCredentials = true;
try {
(...)
}
2/ 在 this article 之后,您需要将 Content-Type 标头设置为 application/json 以便自动解析数据:
Axios 还将 Content-Type 标头设置为 application/json。这使 Web 框架能够自动解析数据。
,Postman 允许您生成使用 axios 重新创建请求所需的代码。
此处的更多信息:https://learning.postman.com/docs/sending-requests/generate-code-snippets/
点击 Postman 右侧的代码图标