首页 > 解决方案 > 如何在 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");

标签: javascriptajaxcurl

解决方案


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);

推荐阅读