I'm building an Express application that uses the Spotify Web API and I'm using ejs as my view engine. I have one ejs page where you click a button and it calls an endpoint in my Express server which redirects a few times (within the same server) using res.redirect()
before finally landing on an endpoint that calls https://accounts.spotify.com/authorize
like this
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))
However, in my browser's inspect window, this is the error I get:
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.
When I make the original call from my ejs page, I use the XMLHttpRequest library and I make the request like so:
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}`)
I also use the CORS package on my server side code like so:
app.use(cors())
Do I need to enable CORS somewhere else or is there something else that I'm missing completely?