我正在使用 SvelteKit 在 localhost:5173 上运行服务器。在前端,当单击按钮时,它会调用我的服务器的
/login
端点。该端点构建查询参数并重定向到 Spotify /Authorize 端点,如其文档中所述。.
我的
/login
端点如下所示(省略客户端 ID):
export function GET(url){
let params = new URLSearchParams({
response_type: 'code',
client_id: '...',
scope: 'playlist-modify-private playlist-read-private',
redirect_uri: `localhost:5173`
});
let endpoint = 'https://accounts.spotify.com/authorize?';
throw new redirect(308, endpoint + params.toString())
}
我得到的回复如下:
Access to fetch at 'https://accounts.spotify.com/authorize?response_type=code&client_id=...&scope=playlist-modify-private+playlist-read-private&redirect_uri=localhost%3A5173' (redirected from 'http://localhost:5173/login') from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我假设我需要设置正确的 CORS 访问源,但我不确定在 SveletKit 中的哪里执行此操作,特别是在抛出重定向时。
因此,当您的应用尝试请求您未指定应允许从该域获取资源的域时,就会发生 CORS。
对此问题的快速“修复”只需安装
cors
软件包:
npm i cors
然后将其添加到您的 Express 应用程序中:
const cors = require('cors');
const app = express();
app.use(cors());
但是,如果您指定要绕过 CORS 的域,则会更安全,如下所示:
app.use(cors({
origin: // List of domains
}));
这里有一个很好的链接,可以更深入地了解这个问题:https://www.section.io/engineering-education/how-to-use-cors-in-nodejs-with-express/