我正在嘗試呼叫端點以在 django 中使用 oauth 生成訪問令牌,當我使用 jquery 呼叫端點時它正在作業,但當我嘗試使用 fetch 呼叫它時它不起作用
這是獲取的代碼
fetch(`https://<domain>/o/token/`, {
method: 'POST',
body:{
grant_type:'password',
client_id: "<client-id>",
client_secret:"<client-secret>",
username:"<username>",
password:"<password>"
}
})
.then(res => res.json())
.then(res => {console.log(res)});
輸出是
{error: 'unsupported_grant_type'}
而當我使用 jquery ajax 呼叫它時,它的作業如下
$.post({
url:'https://<domain>/o/token/',
data:{
grant_type:'password',
client_id: "<client-id>",
client_secret:"<client-secret>",
username:"<username>",
password:"<password>"
},
success: function(data){
console.log(data);
}
})
輸出是
{access_token: '<access-token>', expires_in: 3600, token_type: 'Bearer', scope: 'read write groups', refresh_token: '<refresh-token>'}
uj5u.com熱心網友回復:
如果有人遇到同樣的問題,我已經找到了解決方法
在 jquery ajax 中,如以下代碼塊中所示,它將字典物件轉換為查詢字串
var data = "";
for (var x in option.data) {
if (data != "") {
data = "&";
}
data = encodeURIComponent(x) "=" encodeURIComponent(option.data[x]);
};
option.data = data;
并將內容型別標頭設定為
'application/x-www-form-urlencoded; charset=UTF-8'
因此,將作為 jquery ajax 呼叫作業的正確獲取代碼如下
fetch(`https://<domain>/o/token/`, {
method: 'POST',
headers: {
"Content-Type": 'application/x-www-form-urlencoded; charset=UTF-8'
},
body:'grant_type=password&client_id=<client-id>&client_secret=<client-secret>&username=<username>&password=<password>'
})
.then(res => res.json())
.then(res => {console.log(res)});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/483393.html
