简体   繁体   中英

Fetch post request works but axios post does not?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM