我正在向POST服务器发送请求,以通过 axios 获取Content-Type标头为x-www-form-urlencoded. 我用邮递员试过同样的方法,效果很好。我在请求正文中发送一个 grant_type 和 client_credentials 的键值对。
这是我的 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);
})
Run Code Online (Sandbox Code Playgroud)
数据对象由 client_credentials 组成。相同的凭据在邮递员中给出了成功的响应。
bin*_*ter 12
我遇到了完全相同的问题,直到我最终发现 Axios 需要将数据对象重新格式化为查询字符串。
所以让自己成为这样的函数:
function getQueryString(data = {}) {
return Object.entries(data)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
}
Run Code Online (Sandbox Code Playgroud)
非常简单,只需对对象的所有部分进行 URI 编码并将它们与&.
然后像这样修改你的代码:
axios.post(`${baseURI}/protocol/openid-connect/token`,data, {
headers : {
"Authorization" : "Basic " + token,
"Content-Type" : "application/x-www-form-urlencoded"
},
withCredentials: true,
transformRequest: getQueryString
})
.then(/*...*/);
Run Code Online (Sandbox Code Playgroud)
您可以在此处阅读请求配置的不同选项,包括 transformRequest:https : //github.com/axios/axios#request-config
(我仍然很恼火,这是必要的,不仅由 Axios 处理,而且很好。)
| 归档时间: |
|
| 查看次数: |
6416 次 |
| 最近记录: |