[英]Axios is not working to get access token?
我有 axios 調用來獲取不記名令牌,它是 oauth2.0 但由於某種原因它失敗了相同的調用在 postman 中工作。
index.js
export async function getESLAccessToken(apiConfig: any) {
const _body = {
grant_type: apiConfig.authOptions.body.grant_type,
client_id: apiConfig.authOptions.credentials.sdk_voyage.clientId,
client_secret: apiConfig.authOptions.credentials.sdk_voyage.clientSecret,
scope: apiConfig.authOptions.body.scope
};
const _headers = {
"Content-Type": "application/x-www-form-urlencoded",
"appName": "Blink",
"Accept": "*/*",
"Content-Length": 163
};
const request = {
method: 'POST',
_body,
headers: _headers
};
try {
const resp = await axios.post('https://auth/oauth2/token',
request);
console.log(resp.data);
} catch (err) {
// Handle Error Here
throw err;
}
}
這就是為 axios 構建請求的方式
{
"method": "POST",
"_body": {
"grant_type": "client_credentials",
"client_id": "abc",
"client_secret": "xyz",
"scope": "APPPII APPPHI"
},
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"appName": "Blink",
"Accept": "*/*",
"Content-Length": 163
}
}
錯誤
Error: Request failed with status code 400
Postman 工作請求和響應
POST https://auth/oauth2/token
200
163 ms
POST /auth/oauth2/token HTTP/1.1
Headers
User-Agent: PostmanRuntime/7.26.8
Accept: */*
Cache-Control: no-cache
Postman-Token: d90ccc33-1d77-4502-9a41-74080dd3d7a5
Host: qaapih8.corp.cvscaremark.com
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 163
Request Body
grant_type=client_credentials&client_id=abc&client_secret=xyz&scope=APPPII%20APPPHI
HTTP/1.1 200 OK
響應體
{ "token_type":"Bearer", "access_token":"token returned", "expires_in":3600, "consented_on":164684, "scope":"APPPII APPPHI" }
axios.post
function 的第二個參數應該是請求正文。 第三個參數應該是 Axios 請求配置 object (您可以設置標題)。 Axios POST 請求
在您的情況下,代碼應如下所示:
const body = {
grant_type: apiConfig.authOptions.body.grant_type,
client_id: apiConfig.authOptions.credentials.sdk_voyage.clientId,
client_secret: apiConfig.authOptions.credentials.sdk_voyage.clientSecret,
scope: apiConfig.authOptions.body.scope
};
const myHeaders = {
// add your headers here
}
const response = await axios.post(
'https://auth/oauth2/token',
body,
{ headers: myHeaders }
);
代替
const request = {
method: 'POST',
_body,
headers: _headers
};
和:
const request = {
method: 'POST',
data: _body,
headers: _headers
};
正如評論中的文檔所指出的那樣 session: https://axios-http.com/docs/req_config
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.