问题
I'm trying to retrieve an access token from the Spotify API when making a post request with axios on an Express back end server. So far I have been unsuccessful. I'm getting the following error:
data: { error: 'unsupported_grant_type', error_description: 'grant_type must be client_credentials, authorization_code or refresh_token' } } }
I've already tried to change 'data' property for 'grant_type' to 'params' but it's still not working. Any advice would help.
const express = require('express');
const axios = require('axios');
const dotenv = require('dotenv');
dotenv.config();
const app = express();
const port = 3000;
const client_id = process.env.CLIENT_ID;
const client_secret = process.env.CLIENT_SECRET;
app.get('/spotify-authorization', (req, res) => {
axios({
method: 'post',
url: 'https://accounts.spotify.com/api/token',
data: {
grant_type: 'client_credentials'
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization:
'Basic ' +
Buffer.from(client_id + ':' + client_secret).toString('base64')
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
res.send('successful response received!');
});
app.listen(port, () => console.log(`Express app listening on port ${port}!`));
I want to be able to retrieve the access token in the response from the Spotify API. Please help!
回答1:
From axios docs : By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.
For Nodejs you can use the querystring module as follows:
var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
So, in your case you could try data: querystring.stringify({ grant_type: 'client_credentials' })
回答2:
I can't leave a comment due to low reputation, but 1556089774's answer should be the accepted answer. I've spent over 4 hours researching as to why it wasn't working since Spotify's iOS sdk points to https://glitch.com/~spotify-token-swap as an example which does NOT WORK. Adding the stringify to the data part of the request makes it work:
data: querystring.stringify ({
grant_type: "authorization_code",
redirect_uri: SPOTIFY_CLIENT_CALLBACK_URL,
code: authorization_code
})
来源:https://stackoverflow.com/questions/55460718/error-400-when-making-post-request-to-spotify-api-with-axios-on-express-js