来自原点“http://localhost:3000”已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头

问题描述 投票:0回答:1

我有一个下一个 js 应用程序,我想在其中包含一个部分来显示我当前正在播放的曲目。我创建了一个单独的 Express 应用程序,在其中完成 Spotify 文档中所述的授权过程,并在我在浏览器上调用我的 api 时成功返回我当前播放的曲目以及艺术家和图像。

但是,当我尝试在下一个 js 应用程序上调用它时,出现以下错误:

访问“https://accounts.spotify.com/authorize?response_type=code&client_id=3&scope=user-read-private%20user-read-email%20user-read-currently-playing&redirect_uri=http%3A%2F%”来自原点“http://localhost:3000”的 2Flocalhost%3A8888%2Fapi%2Fcallback&state=2db5053330e577d4'(从“http://localhost:8888/api/login”重定向)已被 CORS 策略阻止:无“访问控制” -Allow-Origin'标头存在于请求的资源上。如果不透明响应满足您的需求,请将请求模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。 审判.tsx:31

注意:当我从浏览器调用 api 时没有错误(我什至将其部署在 vercel 上并且它可以工作)。我的退货方式可能有问题(?)。

我尝试在服务器端以及下一个 js api 调用中添加 cors 中间件,但似乎没有任何效果。

这是我的 /api/login 路由,名为 login.js:


const login = require('express').Router();
const querystring = require('querystring');
const cors = require('cors');


const corsOptions = {
    origin: '*',
    credentials: true
}


login.use(cors(corsOptions));


const stateKey = 'spotify_auth_state';


login.get("/", (req, res) => {
    const state = generateRandomString(16);
    res.cookie(stateKey, state);

    // your application requests authorization
    const scope = 'user-read-private user-read-email user-read-currently-playing';
    res.redirect('https://accounts.spotify.com/authorize?' +
        querystring.stringify({
        response_type: 'code',
        client_id: client_id,
        scope: scope,
        redirect_uri: redirect_uri,
        state: state
    }));
});


这里是回调路由(/api/callback):

const callback = require('express').Router();
const querystring = require('querystring');
const request = require('request');
const bodyparser = require('body-parser');
const cors = require('cors');

require('dotenv').config();


callback.use(cors({
  origin: 'http://localhost:3000',
  credentials: true
}));

callback.use(bodyparser.json());


const stateKey = 'spotify_auth_state';

callback.get('/', (req, res) => {


        /* ...callback code to get the authorization token ... */


        //here i return the info once i get it
        // use the access token to access the Spotify Web API
        request.get(options, function(error, response, body) {
          console.log(body);
          res.set('Content-Type', 'application/json');
          res.set('Access-Control-Allow-Origin', 'http://localhost:3000');
          
          
          if (body) {
            res.status(200).json({ 
              name: body.item.name, 
              artist: body.item.artists[0].name, 
              album: body.item.album.name, 
              image: body.item.album.images[0].url
            });
          } else {
            res.status(200).json({ name: '', artist: '', album: '', image: ''})
          }

        });
        
  

});

这是我如何在下一个 js(页面路由器)上进行 api 调用:

const apiCall = async () => {
    try {
      const res = await fetch('http://localhost:8888/api/login', {
        method: 'GET',
        mode: 'cors',
        credentials: 'include',
      })

      const data = await res.json();
    } catch (error) {
      console.error('API CALL: Error fetching currently playing song:', error.message);
    }
  }`
express next.js cors spotify
1个回答
0
投票

正如您所提到的,它可以在 vercel 上运行,但不能在 localhost:3000 上运行。

尝试在浏览器中添加“CORS Unblock”插件并测试一次。

© www.soinside.com 2019 - 2024. All rights reserved.