Search code examples
node.jsexpressspotify

Spotify Api Auth unsupported_grant_type


I'm working on integrating spotify and I'm making my own api. I can't understand why my request is not working. It works fine in python but not when I use express. I get this response body :

{"error":"unsupported_grant_type","error_description":"grant_type must be client_credentials, authorization_code or refresh_token"}

Express :

var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var fetch = require('node-fetch');

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }))

app.listen(80);

app.post('/v1/spotify/api/token', function(req, res) {

    let body = req.body
    let redirect_uri = body.redirect_uri
    let code = body.code

    let data = {
        grant_type:'authorization_code',
        redirect_uri:redirect_uri,
        code:code
    }

    fetch('https://accounts.spotify.com/api/token', {
        method: 'POST',
        headers: {
            'Authorization':'Basic *client_id:client_secret*',
            'Content-Type':'application/x-www-form-urlencoded'
        },
        body: JSON.stringify(data)
    }).then(r =>  r.json().then(data => res.send(data)))
});

Python:

r = requests.post("https://accounts.spotify.com/api/token",
data={
    "grant_type":"authorization_code",
    "redirect_uri":*redirect_uri*,
    "code":*code*
},
headers = {
    "Authorization": "Basic *client_id:client_secret*",
    'Content-Type':'application/x-www-form-urlencoded'}
)

Solution

  • In your script of Node.js, data is sent as a string value. So how about this modification?

    Modified script

    Please modify the object of data as follows and try again.

    // Below script was added.
    const {URLSearchParams} = require('url');
    const data = new URLSearchParams();
    data.append("grant_type", "authorization_code");
    data.append("redirect_uri", redirect_uri);
    data.append("code", code);
    
    fetch('https://accounts.spotify.com/api/token', {
        method: 'POST',
        headers: {
            'Authorization':'Basic *client_id:client_secret*',
            'Content-Type':'application/x-www-form-urlencoded'
        },
        body: data // Modified
    }).then(r =>  r.json().then(data => res.send(data)))
    

    Reference:

    If this didn't work, I apologize.