Spotify Api 授权 unsupported_grant_type

Spotify Api Auth unsupported_grant_type

我正在努力整合 spotify,并且正在制作自己的 api。我不明白为什么我的请求不起作用。它在 python 中工作正常,但在我使用 express 时却不行。 我收到了这个回复正文:

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

快递:

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

在您的 Node.js 脚本中,data 作为字符串值发送。那么这个修改怎么样呢?

修改脚本

请修改data的对象如下,然后重试

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

参考:

如果这不起作用,我深表歉意。