【发布时间】:2019-10-22 15:30:31
【问题描述】:
我正在构建一个使用 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))
但是,在我的浏览器的检查窗口中,这是我得到的错误:
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,还是我完全缺少其他东西?
【问题讨论】:
标签: node.js express cors xmlhttprequest spotify