启用 CORS 不适用于 Spotify Web API

Enabling CORS not working with Spotify Web API

我正在构建一个使用 Spotify Web API 的 Express 应用程序,并且我正在使用 ejs 作为我的视图引擎。我有一个 ejs 页面,您在其中单击一个按钮,它调用我的 Express 服务器中的一个端点,该端点使用 res.redirect() 重定向几次(在同一服务器内),然后最终登陆一个调用 https://accounts.spotify.com/authorize 的端点这个

res.redirect('https://accounts.spotify.com/authorize' +
      '?response_type=code' +
      '&client_id=' + process.env.SPOTIFY_CLIENT_ID +
      (scopes ? '&scope=' + encodeURIComponent(scopes) : '') +
      '&redirect_uri=' + encodeURIComponent(process.env.SPOTIFY_REDIRECT_URI))

但是,在我的浏览器检查 window 中,这是我得到的错误:

Access to XMLHttpRequest at 'https://accounts.spotify.com/authorize?{my params here}' (redirected from 'http://localhost:5000/login') from origin 'http://localhost:5000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

当我从我的 ejs 页面进行原始调用时,我使用了 XMLHttpRequest 库并像这样发出请求:

xhttp.open("POST", "http://localhost:5000/login", true)
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
xhttp.setRequestHeader('Access-Control-Allow-Origin', '*')
xhttp.setRequestHeader('Access-Control-Allow-Method', 'GET, POST, PATCH, PUT, DELETE, OPTIONS')
xhttp.setRequestHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token')
xhttp.send(`email=${email}&password=${password}`)

我还在我的服务器端代码中使用 CORS 包,如下所示:

app.use(cors())

我是否需要在其他地方启用 CORS,或者是否还有其他我完全遗漏的东西?

1) 从您的客户端(ejs 页面)拨打电话时,您不必发送 Access-Control-* headers。

2) 服务器需要返回 Access-Control-* headers 以允许 CORS。服务器还需要先处理 'OPTIONS' 请求。通常,我在不使用 cors 中间件的情况下这样做:

// Enabling CORS
app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "*");

  if (req.method === "OPTIONS") {
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH");
    return res.status(200).json({});
  }
  next();
});

使用 * 不是一个好习惯,并且在浏览器需要接受 cookie 的情况下不允许使用。但是您现在可以使用它来测试您的 api.

以上使用cors中间件也可以实现。 下面一行:

app.use(cors())

在将请求发送到任何 route/controller 之前只应添加一次。 这可确保为每个响应实际添加允许 CORS 所需的 headers。

更新: 如果你想从你的浏览器访问 spotify 页面,它应该从你的客户端(ejs 页面)重定向。从您的服务器获取必要的数据并使用它从您的客户端重定向。