【问题标题】:Sending post request from axios with "Content-Type" : "application/x-www-form-urlencoded" gives an 401 Unauthorized response从 axios 发送带有“Content-Type”的 post 请求:“application/x-www-form-urlencoded”给出 401 Unauthorized 响应
【发布时间】:2019-08-10 00:33:41
【问题描述】:

我正在向服务器发送一个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组成。相同的凭据在邮递员中给出了成功的响应。

【问题讨论】:

    标签: node.js axios


    【解决方案1】:

    我遇到了同样的问题,直到我最终发现 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 处理,而且很好。)

    【讨论】:

    • 工作就像一个魅力。非常感谢。
    猜你喜欢
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 2019-08-15
    • 2014-03-30
    • 2017-09-22
    • 2016-02-18
    • 2013-11-10
    相关资源
    最近更新 更多