NodeJS Spotify API“播放器/当前正在播放”端点未返回设备响应

6jygbczu  于 2023-03-22  发布在  Node.js
关注(0)|答案(1)|浏览(177)
app.get("/api", (req, res) => {
  callEndpoint("get", CURRENTLYPLAYING + "?market=US", null, (response) => {
    let data = response.data
    let newData = {}

    newData.volume = data.device.volume_percent // device is undefined

    res.status(200).json(newData)
  })
})

我期望设备被定义,正如API文档中所说的那样,但它不存在于响应中

tjjdgumg

tjjdgumg1#

Get Currently Playing Track不再提供设备信息,您必须使用Get Available Devices
它必须使用Authorization Code Flow
最后,您必须使用user-read-playback-stateScope

此演示代码将显示设备信息

保存为server.js文件名。

const axios = require('axios')
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors())

// for raw JSON of Body
app.use(express.json()); 

const REDIRECT_URI='<your redirect URL>' // mine is http://localhost:3000/callback
const CLIENT_ID='<your client id>'
const CLIENT_SECRET='<your client secret>'
const SCOPE=['user-read-currently-playing','user-read-playback-state']

app.get("/login", (request, response) => {
    const redirect_url = `https://accounts.spotify.com/authorize?response_type=code&client_id=${CLIENT_ID}&scope=${SCOPE}&state=123456&redirect_uri=${REDIRECT_URI}&prompt=consent`
    response.redirect(redirect_url);
})

app.get("/callback", async (request, response) => {
    const code = request.query["code"]
    await axios.post(
        url = 'https://accounts.spotify.com/api/token',
        data = new URLSearchParams({
            'grant_type': 'authorization_code',
            'redirect_uri': REDIRECT_URI,
            'code': code
        }),
        config = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            params: {
                'grant_type': 'client_credentials'
            },
            auth: {
                username: CLIENT_ID,
                password: CLIENT_SECRET
            }
        })
        .then(resp1 => {
            axios.get(
                // url = 'https://api.spotify.com/v1/me/player/currently-playing',
                url = 'https://api.spotify.com/v1/me/player/devices',
                config = {
                    headers: {
                        'Accept-Encoding': 'application/json',
                        Authorization: `Bearer ${resp1.data.access_token}`
                    }
                }
            ).then(resp2 => {
                return response.send(JSON.stringify(resp2.data));
            })
        });

})
// use your <your redirect URL>'s port
app.listen(3000, () => { console.log("Listening on : 3000") })

安装依赖

npm install axios express cors

运行服务器

node server.js

通过浏览器登录获取token

http://localhost:3000/login

结果

相关问题