簡體   English   中英

使用“Content-Type”:“application/x-www-form-urlencoded”從 axios 發送帖子請求會給出 401 Unauthorized 響應

[英]Sending post request from axios with "Content-Type" : "application/x-www-form-urlencoded" gives an 401 Unauthorized response

我正在向服務器發送POST請求以通過 axios 獲取令牌, Content-Typex-www-form-urlencoded header。 我對 postman 進行了同樣的嘗試,效果很好。 我在請求正文中發送了一對鍵值對 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);
})

數據 object 由 client_credentials 組成。相同的憑據在 postman 中給出了成功的響應。

我有這個完全相同的問題,直到我終於發現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處理,但很好。)

雖然@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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM