Fetch post request works but axios post does not?

谁都会走 提交于 2021-01-29 20:39:57

问题


Currently trying to convert a working fetch POST request into an Axios POST request, however, I keep getting the error "Error: Request failed with status code 400". The function is a post request to the Spotify API to obtain an authentication token. Would greatly appreciate any help :)

This is the current Fetch POST request that works:

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',
});

My current Axios POST request that does not work:

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

I've also tried using the axios.post method:

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:


thanks @trincot, using data instead of body works

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


来源:https://stackoverflow.com/questions/63594293/fetch-post-request-works-but-axios-post-does-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!