gpt4 book ai didi

node.js - 使用 NextJS 的 api 路由实现 Spotify 的授权流程会抛出 cors 错误

转载 作者:行者123 更新时间:2023-12-05 05:56:36 25 4
gpt4 key购买 nike

我正尝试在 NextJS 中创建登录流程,如下所述:Spotify SDK API Tutorial,使用 NextJS 的 api 路由

我创建了两个处理程序:api/login.tsapi/callback.ts

login.ts 处理调用 spotify 授权端点所需的参数构造。callback.ts 处理来自授权服务器的重定向 url。它解析请求并发回数据。

当我访问路径时:localhost:3000/api/login 它很好地解析了响应并向我发送了所需的access_tokenrefresh_token 在响应中。响应在浏览器中显示为 JSON。

现在,当我在组件中调用此端点时,问题就出现了。我在那里获取“/api/login”端点(参见:Login.tsx),但它抛出以下 cors 错误:

获取在'https://accounts.spotify.com/authorize/?response_type=code&client_id=woops&scope=streaming+user-read-email+user-read-private&redirect_uri=http%3A%2F%来自“http://localhost:3000”的 2Flocalhost%3A3000%2Fapi%2Fcallback&state=woops(从“http://localhost:3000/api/login”重定向)已被 CORS 策略阻止:无“访问控制” -Allow-Origin' header 出现在请求的资源上。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

登录.ts:

import type { NextApiRequest, NextApiResponse } from 'next'

const generateRandomString = (length: number): string => {
let text = '';
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

for (var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
};

const scope = "streaming \
user-read-email \
user-read-private";

export default async function login(
req: NextApiRequest,
res: NextApiResponse
) {

const state = generateRandomString(16);

const input = {
response_type: "code",
client_id: process.env.SPOTIFY_CLIENT_ID,
scope,
redirect_uri: "http://localhost:3000",
state,
} as Record<string, string>;

const auth_query_parameters = new URLSearchParams(input)
res.redirect(`https://accounts.spotify.com/authorize/?${auth_query_parameters.toString()}`);
}

回调.ts:

import type { NextApiRequest, NextApiResponse } from 'next'

const formBody = (details: Record<string, string>): string => {
return Object.keys(details)
.map(key => encodeURIComponent(key) + '=' + encodeURIComponent(details[key]))
.join('&')
}

export default function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const { code } = req.query;

const spotifyURL = 'https://accounts.spotify.com/api/token';

const formData = {
code: code,
redirect_uri: "http://localhost:3000/api/callback",
grant_type: 'authorization_code'
} as Record<string, string>;

const config = {
method: 'POST',
headers: {
'Authorization': 'Basic ' + (Buffer.from(process.env.SPOTIFY_CLIENT_ID + ':' + process.env.SPOTIFY_CLIENT_SECRET).toString('base64')),
'Content-Type' : 'application/x-www-form-urlencoded'
},
body: formBody(formData),
JSON: true
};

fetch(spotifyURL, config as RequestInit)
.then(response => response.json())
.then(data => {
res
.send(data)
})
}

登录.tsx

import { useEffect, useState } from "react";
import Login from '../components/Login';
import WebPlayback from '../components/WebPlayback';

const useLogin = () => {
const [token, setToken] = useState('');

useEffect(() => {
async function getToken() {
const response = await fetch('/api/login', { mode: 'cors' });
const json = await response.json();
setToken(json.access_token)
}
getToken();
}, []);

return token;
}

const App = () => {
const token = useLogin();
return (
<>
{
token === ''
? <Login />
: <WebPlayback token={token} />
}
</>
)
}

export default App;

最佳答案

将你的模式设置为no-cors

const response = await fetch('/api/login', { mode: 'no-cors' });

关于node.js - 使用 NextJS 的 api 路由实现 Spotify 的授权流程会抛出 cors 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69136330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com