You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Express实现Spotify API授权的Client Credentials Flow?

基于Express + Axios实现Spotify Client Credentials Flow方案

前置准备

  • 提前在Spotify开发者后台注册应用,获取你的Client ID和Client Secret
  • 本地开发环境安装Node.js 14及以上版本

安装依赖

执行以下命令安装所需第三方包:

npm install express axios dotenv

代码实现

  1. 首先在项目根目录新建.env配置文件,写入如下内容:
CLIENT_ID = 你从Spotify后台获取的Client ID
CLIENT_SECRET = 你从Spotify后台获取的Client Secret
PORT = 3000
  1. 新建入口文件app.js,完整代码如下:
require('dotenv').config();
const express = require('express');
const axios = require('axios');
const app = express();

// 封装获取访问令牌的方法
async function getSpotifyAccessToken() {
  const authHeader = Buffer.from(
    `${process.env.CLIENT_ID}:${process.env.CLIENT_SECRET}`
  ).toString('base64');

  try {
    const response = await axios.post(
      'https://accounts.spotify.com/api/token',
      new URLSearchParams({ grant_type: 'client_credentials' }),
      {
        headers: {
          'Authorization': `Basic ${authHeader}`,
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }
    );
    return response.data.access_token;
  } catch (err) {
    console.error('获取令牌失败:', err.response?.data || err.message);
    throw err;
  }
}

// 测试接口:获取Spotify新歌榜数据
app.get('/api/new-releases', async (req, res) => {
  try {
    const accessToken = await getSpotifyAccessToken();
    const result = await axios.get(
      'https://api.spotify.com/v1/browse/new-releases',
      {
        headers: { 'Authorization': `Bearer ${accessToken}` }
      }
    );
    res.json(result.data);
  } catch (err) {
    res.status(500).json({ error: '请求失败' });
  }
});

app.listen(process.env.PORT, () => {
  console.log(`服务运行在 http://localhost:${process.env.PORT}`);
});

使用说明

  • 令牌有效期默认1小时,你可以将获取到的令牌存储到内存或者Redis缓存中,避免每次接口请求都重复申请令牌
  • 不要将.env文件提交到代码仓库,避免泄露你的Client Secret
  • 启动服务后访问http://localhost:3000/api/new-releases即可测试接口是否正常返回数据

内容的提问来源于stack exchange,提问作者Ritvik Biswas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 08:33:00