node.js - 使用“Content-Type”从 axios 发送 post 请求:“application/x-www-form-urlencoded”给出 401 Unauthorized 响应
问题描述
我正在向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);
})
数据对象由 client_credentials 组成。相同的凭据在邮递员中给出了成功的响应。
解决方案
在我最终发现 Axios 需要将数据对象重新格式化为查询字符串之前,我遇到了同样的问题。
所以给自己做一个这样的函数:
function getQueryString(data = {}) {
return Object.entries(data)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
}
非常简单,只需对对象的所有部分进行 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(/*...*/);
您可以在此处阅读有关请求配置的不同选项,包括 transformRequest:https ://github.com/axios/axios#request-config
(我仍然很恼火,这是必要的,不仅由 Axios 处理,而且很好。)
推荐阅读
- javascript - 无法在春季项目上显示 Summernote 文本区域
- python-3.x - 如何从命令提示符执行在 IDE 上制作的 python 程序
- java - Spring Security OAuth2 客户端的意外行为
- postgresql - 比较和删除同一张表中的记录
- python-3.x - 为什么不能同时运行 tkinter mainloop 和 cefpython3 messageloop?
- django - 在 Django 中创建通用搜索视图
- r - 预测现有时间序列数据
- python - 如何在 Pandas DataFrame 中操作来自 Google AutoML 的预测响应?
- node.js - 响应标头中 Content-Type 的用途是什么?
- java - 升级database_version时重命名sqlite数据库的列