[英]Sending post request from axios with "Content-Type" : "application/x-www-form-urlencoded" gives an 401 Unauthorized response
I am sending a POST
request to a server to fetch a token through axios with a Content-Type
header of x-www-form-urlencoded
.我正在向服务器发送
POST
请求以通过 axios 获取令牌, Content-Type
为x-www-form-urlencoded
header。 I tried the same with postman and it works fine.我对 postman 进行了同样的尝试,效果很好。 I'm sending a key value pair of grant_type and client_credentials in the request body.
我在请求正文中发送了一对键值对 grant_type 和 client_credentials。
This is my axios request:这是我的 axios 请求:
axios.post(`${baseURI}/protocol/openid-connect/token`, data, {
headers : {
"Authorization" : "Basic " + token,
"Content-Type" : "application/x-www-form-urlencoded"
},
withCredentials: true
}).then(response => {
AUTH_TOKEN = response.data.access_token;
console.log(response.data);
}).catch(error => {
console.log(error.response);
})
The data object consists of the client_credentials.The same credentials gives a successful response in postman.数据 object 由 client_credentials 组成。相同的凭据在 postman 中给出了成功的响应。
I had this exact same problem until I finally figured out that Axios needed the data object to be reformatted as a query string. 我有这个完全相同的问题,直到我终于发现Axios需要将数据对象重新格式化为查询字符串。
So make yourself a function like this: 所以让自己成为这样的函数:
function getQueryString(data = {}) {
return Object.entries(data)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
}
Pretty simple, just URI encoding all the parts of your object and joining them with &
. 非常简单,只是URI编码对象的所有部分并使用
&
连接它们。
Then modify your code like this: 然后像这样修改你的代码:
axios.post(`${baseURI}/protocol/openid-connect/token`,data, {
headers : {
"Authorization" : "Basic " + token,
"Content-Type" : "application/x-www-form-urlencoded"
},
withCredentials: true,
transformRequest: getQueryString
})
.then(/*...*/);
You can read about the different options, including transformRequest, for the request config here: https://github.com/axios/axios#request-config 您可以在此处阅读有关请求配置的不同选项(包括transformRequest): https : //github.com/axios/axios#request-config
(I'm still annoyed that this was necessary and not just handled by Axios but oh well.) (我仍然很生气,这是必要的,不仅仅是由Axios处理,但很好。)
While @binary lobster
solution is pretty concise, one might consider using qs
library like this:虽然
@binary lobster
解决方案非常简洁,但可以考虑像这样使用qs
库:
import qs from 'qs'
axios.post(`${baseURI}/protocol/openid-connect/token`,
qs.stringify(data), {
headers : {
"Authorization" : "Basic " + token,
"Content-Type" : "application/x-www-form-urlencoded"
}
})
.then(/*...*/);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.