javascript - 如何在 Javascript 中向 API 请求添加请求正文参数?
问题描述
我正在使用 Spotify API 并且需要获取访问令牌,尽管示例/指南(https://developer.spotify.com/documentation/general/guides/authorization-guide/#client-credentials-flow)是用cURL,我需要将其转换为 Javascript。
主要问题是将请求主体参数“grant_type”设置为“client_credentials”,并且“此 POST 请求的主体必须包含在 application/x-www-form-urlencoded 中编码的以下参数,如 OAuth 2.0 规范中定义的那样:”我不知道该怎么做。
我已经在命令提示符下尝试了 cURL,它工作正常,但我不会使用 cURL。
我正在尝试做的事情
curl -X "POST" -H "Authorization: Basic ZjM4ZjAw...WY0MzE=" -d grant_type=client_credentials https://accounts.spotify.com/api/token
我有的
var auth_id = "";
var getToken = new XMLHttpRequest();
getToken.open('POST', 'https://accounts.spotify.com/api/token', true);
getToken.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
getToken.setRequestHeader('grant_type', 'client_credentials'); //this param needs to be in body but how???
getToken.setRequestHeader('Authorization', 'Basic (this part is my client id but I am not including it for obvious reasons)');
getToken.onload = function (){
var data = JSON.parse(this.response);
console.log(data);
auth_id=data.access_token;
}
getToken.send("client_credentials");
解决方案
I would recommend you to use a more modern fetch
api like native fetch
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API or a third party library like axios
https://github.com/axios/axios
Using fetch
it is fairly easy
const url = 'https://accounts.spotify.com/api/token';
const request = new Request(url, {
headers: new Headers({
Authorization: 'Basic XXX',
}),
body: JSON.stringify({
grant_type: 'client_credentials'
}),
method: 'POST',
);
const response = await fetch(request);
推荐阅读
- oracle - 同步 oracle ddl 更改
- typescript - 打字稿合并类型
- r - if (randomNumber <= p) { 中的错误:需要 TRUE/FALSE 的缺失值
- php - 从数组中提取元素,其键以 PHP 中的特定 id 结尾
- javascript - 获取多个触摸结束事件javascript
- powershell - 如何在 Powershell 中过滤(json)数组?
- javascript - 如何根据三个分隔符拆分字符串?
- javascript - 如何在 php 中使用 javascript 函数?
- visual-studio-code - 如何摆脱 vscode 远程开发?
- javascript - 单击编辑器上的工具栏按钮时,不将焦点放在 Froala 编辑器上的编程方法是什么。 $el (textarea)