我不确定为什么当我尝试使用 Express Fetch API 获取精选播放列表时会收到 500 内部服务器错误。我知道这可能与 Spotify 令牌调用有关。我不确定哪里出了问题。
我尝试使用客户端凭据授权方法使用 Spotify API 获取特色播放列表。我收到的不是播放列表,而是 500 内部服务器错误。这是我的代码
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const PORT = 3001;
const app = express();
const corsOptions = {
origin: "http://localhost:3000",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true,
};
app.use(cors(corsOptions));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const fetch = import("node-fetch").then((module) => module.default);
const CLIENT_ID = "******";
const CLIENT_SECRET = "*******";
const SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token";
const SPOTIFY_PLAYLISTS_URL = "https://api.spotify.com/v1/browse/featured-playlists";
async function getSpotifyToken() {
const response = await fetch(SPOTIFY_TOKEN_URL, {
method: "POST",
headers: {
Authorization: "Basic " + Buffer.from(CLIENT_ID + ":" + CLIENT_SECRET).toString("base64"),
"Content-Type": "application/x-www-form-urlencoded",
},
body: "grant_type=client_credentials",
json: true,
});
if (response.ok) {
const jsonResponse = await response.json();
console.log(jsonResponse);
} else {
console.log(response.statusText);
throw new Error(
`Request failed! Status code: ${response.status} ${response.statusText}`
);
}
}
async function getPlaylistInfo(accessToken) {
const endpoint = SPOTIFY_PLAYLISTS_URL;
const options = {
method: "GET",
headers: {
Authorization: "Bearer" + accessToken,
},
};
try {
const response = await fetch(endpoint, options);
console.log("Spotify API Response Status:", response.status);
console.log("Spotify API Response Headers:", response.headers.raw());
if (response.ok) {
const data = await response.json();
console.log("Spotify API Data:", data);
return data;
} else {
console.error("Error fetching playlist from Spotify:", response.status, await response.text() );
throw new Error("Error fetching playlist from Spotify");
}
} catch (error) {
console.error("Error during Spotify API request:", error.message);
throw error;
}
}
app.use(async (req, res, next) => {
try {
const tokenData = await getSpotifyToken();
if (tokenData.access_token) {
req.spotifyAccessToken = tokenData.access_token;
next();
} else {
console.error("Error obtaining Spotify access token:", tokenData);
res.status(tokenResponse.status).json({
error: "Error obtaining Spotify access token"
});
}
} catch (error) {
console.error("Error obtaining Spotify access token:", error.message);
res.status(500).json({
error: "Error obtaining Spotify access token",
details: error.message,
});
}
});
app.get("/api/featuredplaylists", async (req, res) => {
try {
const playlistInfo = await getPlaylistInfo(req.spotifyAccessToken);
res.json(playlistInfo);
} catch (error) {
res.status(500).json({
error: "Error fetching playlist from Spotify",
details: error.message,
});
}
});
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
您的代码需要在几个地方进行修复。
#1 Bearer 和 token 之间没有空格
之前
Authorization: "Bearer" + accessToken,
之后
Authorization: "Bearer " + accessToken,
#2 getSpotifyToken() 中没有返回响应
之前
if (response.ok) {
const jsonResponse = await response.json();
console.log(jsonResponse);
}
之后
if (response.ok) {
const jsonResponse = await response.json();
console.log(jsonResponse);
return jsonResponse;
}
#3 凭证而不是 base64
之前
headers: {
Authorization: "Basic " + Buffer.from(CLIENT_ID + ":" + CLIENT_SECRET).toString("base64"),
"Content-Type": "application/x-www-form-urlencoded",
},
body: "grant_type=client_credentials",
之后
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: 'grant_type=client_credentials&client_id=' + CLIENT_ID + '&client_secret=' + CLIENT_SECRET,
#4 使用打字模式
在package.json中
{
"type": "module",
"dependencies": {
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"express": "^4.18.2",
"node-fetch": "^3.3.2"
}
}
这里有完整的代码 另存为
get-song.js
import express from "express";
import bodyParser from "body-parser";
import cors from "cors";
import fetch from "node-fetch";
const PORT = 3001;
const app = express();
const corsOptions = {
origin: "http://localhost:3000",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true,
};
app.use(cors(corsOptions));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const CLIENT_ID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const CLIENT_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token";
const SPOTIFY_PLAYLISTS_URL = "https://api.spotify.com/v1/browse/featured-playlists";
async function getSpotifyToken() {
const response = await fetch(SPOTIFY_TOKEN_URL, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: 'grant_type=client_credentials&client_id=' + CLIENT_ID + '&client_secret=' + CLIENT_SECRET,
json: true,
});
if (response.ok) {
const jsonResponse = await response.json();
console.log(jsonResponse);
return jsonResponse;
} else {
console.log(response.statusText);
throw new Error(
`Request failed! Status code: ${response.status} ${response.statusText}`
);
}
}
async function getPlaylistInfo(accessToken) {
const endpoint = SPOTIFY_PLAYLISTS_URL;
const options = {
method: "GET",
headers: {
Authorization: "Bearer " + accessToken,
},
};
try {
const response = await fetch(endpoint, options);
console.log("Spotify API Response Status:", response.status);
console.log("Spotify API Response Headers:", response.headers.raw());
if (response.ok) {
const data = await response.json();
console.log("Spotify API Data:", JSON.stringify(data));
return data;
} else {
console.error("Error fetching playlist from Spotify:", response.status, await response.text());
throw new Error("Error fetching playlist from Spotify");
}
} catch (error) {
console.error("Error during Spotify API request:", error.message);
throw error;
}
}
app.use(async (req, res, next) => {
try {
const tokenData = await getSpotifyToken();
if (tokenData.access_token) {
req.spotifyAccessToken = tokenData.access_token;
next();
} else {
console.error("Error obtaining Spotify access token:", tokenData);
res.status(tokenResponse.status).json({
error: "Error obtaining Spotify access token"
});
}
} catch (error) {
console.error("Error obtaining Spotify access token:", error.message);
res.status(500).json({
error: "Error obtaining Spotify access token",
details: error.message,
});
}
});
app.get("/api/featuredplaylists", async (req, res) => {
try {
const playlistInfo = await getPlaylistInfo(req.spotifyAccessToken);
res.json(playlistInfo);
} catch (error) {
res.status(500).json({
error: "Error fetching playlist from Spotify",
details: error.message,
});
}
});
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
安装依赖项
npm install
运行它
node get-song.js
访问它
http://localhost:3001/api/featuredplaylists