简单的 Next.js 组件,显示当前在 Spotify 上播放的歌曲。
背景: 使用应用程序路由器
因为要获取令牌,spotify 要求我进行服务器端调用,因此我发出完整的请求以从 api 端点获取歌曲
localhost/api/player
const getAccessToken = async () => {
const client_id = 'key'; // Replace with your client ID
const client_secret = 'key'; // Replace with your client secret
fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${btoa(`${client_id}:${client_secret}`)}`,
},
body: 'grant_type=client_credentials'
})
.then(response => response.json())
.then(data => {
console.log(data.access_token);
return data.access_token;
});
return null;
}
export const fetchCurrentPlayingSong = async () => {
const accessToken = await getAccessToken();
const response = await fetch('https://api.spotify.com/v1/me/player/currently-playing', {
headers: {
'Authorization': `Bearer ${accessToken}`
}
});
if (!response.ok) {
throw new Error(`Failed to fetch currently playing song: ${response.statusText}`);
}
const song = await response.json();
return song;
};
错误:
未处理的运行时错误
错误:默认导出不是页面中的 React 组件:“/api/player”
我尝试在客户端运行此程序,但 Spotify 不允许在客户端获取令牌。 我只想每 5 秒从服务器获取有关当前播放歌曲的服务器端属性 或显示当前播放歌曲的最佳方式
上下文:使用应用程序路由器
您可能在 api 文件夹中将文件名命名为
page.ts
。你的结构是这样的
app/api/get-token/page.ts
api 文件名为
route.ts
。你应该有
app/api/get-token/route.ts