[英]Trying to get access token with django-oauth-toolkit using fetch not working while working using jquery
I'm trying to call endpoint to generate access token using oauth in django it is working when I call the endpoint using jquery but not working when I try to call it with fetch我正在尝试调用端点以在 django 中使用 oauth 生成访问令牌,当我使用 jquery 调用端点时它正在工作,但当我尝试使用 fetch 调用它时它不起作用
here is the code for 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)});
the output is输出是
{error: 'unsupported_grant_type'}
while when I'm calling it using jquery ajax as below its working而当我使用 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);
}
})
the output is输出是
{access_token: '<access-token>', expires_in: 3600, token_type: 'Bearer', scope: 'read write groups', refresh_token: '<refresh-token>'}
I have found the fix in case someone faced the same problem如果有人遇到同样的问题,我已经找到了解决方法
in jquery ajax as in the following code block it converts the dictionary object to query string在 jquery ajax 中,如以下代码块中所示,它将字典对象转换为查询字符串
var data = "";
for (var x in option.data) {
if (data != "") {
data += "&";
}
data += encodeURIComponent(x)+"="+encodeURIComponent(option.data[x]);
};
option.data = data;
and it sets the content-type header to并将内容类型标头设置为
'application/x-www-form-urlencoded; charset=UTF-8'
so the right fetch code that will work as the jquery ajax call will be as follow因此,将作为 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)});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.