获取帖子请求有效,但axios帖子无效吗?

时间:2020-08-26 09:09:46

标签: javascript api post axios fetch

当前尝试将工作中的提取POST请求转换为Axios POST请求,但是,我一直收到错误消息“错误:请求失败,状态码为400”。该功能是对Spotify API的发布请求,以获取身份验证令牌。非常感谢您的帮助:)

这是当前有效的Fetch POST请求:

const result = await fetch('https://accounts.spotify.com/api/token', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    Authorization: 'Basic ' + btoa(this.clientId + ':' + this.clientSecret),
  },
  body: 'grant_type=client_credentials',
});

我当前的无效的Axios POST请求

const result = await axios({
  url: 'https://accounts.spotify.com/api/token',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    Authorization: 'Basic ' + btoa(this.clientId + ':' + this.clientSecret),
  },
  body: 'grant_type=client_credentials',
}).catch((error) => console.log(error));

我也尝试过使用axios.post方法:

const result = await axios.post('https://accounts.spotify.com/api/token', null, {
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    Authorization: 'Basic ' + btoa(this.clientId + ':' + this.clientSecret),
  },
  body: 'grant_type=client_credentials',
});

1 个答案:

答案 0 :(得分:0)

感谢@trincot,使用数据代替了身体

const result = await axios({
  url: "https://accounts.spotify.com/api/token",
  method: "POST",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    Authorization: "Basic " + btoa(this.clientId + ":" + this.clientSecret),
  },
  data: "grant_type=client_credentials",
}).catch((error) => console.log(error.response));