I'm trying to use Vue & Express to create a simple website using Spotifys API, however when I make a request to the Spotify API, I always get a CORS error:
Access to XMLHttpRequest at 'https://accounts.spotify.com/authorize?response_type=code&client_id=xxx&scope=user-read-playback-state%20user-modify-playback-state&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fapi%2Fauth%2Fcallback&state=E7yOcfaGhTaYJpxV' (redirected from 'http://localhost:5000/api/auth/login?redirect=http%3A%2F%2Flocalhost%3A8080%2F') from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My Vue app is running on port 8080 and my Express server on port 5000.
Currently, the code looks the like this:
Login.vue
public loginClick = async() => {
try {
const response = await AuthService.loginToSpotify()
return response.data.success
} catch (err) {
this.error = err.message
return false
}
}
AuthService.ts
class AuthService {
static loginToSpotify = async () => {
try {
return await axios.get(`${url}/login?` + qs.stringify({ redirect: window.location.origin + window.location.pathname }))
} catch (error) {
return error
}
}
}
And on the server
router.get('/login', (req, res) => {
const state = generateRandomString(16);
res.cookie(stateKey, state);
res.cookie(redirectKey, req.query.redirect);
const scope = 'user-read-playback-state user-modify-playback-state'
return res.redirect('https://accounts.spotify.com/authorize?' +
queryString.stringify({
response_type: 'code',
client_id: config.clientId,
scope,
redirect_uri: redirectUri,
state
}))
})
I've also got cors enabled in index.ts of the server and vue.config.js set up like this
module.exports = {
devServer: {
proxy: 'http://localhost:5000'
}
}
server/index.ts
import express, { Application } from 'express';
import authController from './controllers/auth';
import cookieParser from 'cookie-parser';
import session from 'express-session';
import config from './config';
import redis from 'redis';
import connectRedis from 'connect-redis';
import { generateRandomString } from './lib';
import cors from 'cors';
const app: Application = express();
app.use(cookieParser());
app.use(cors());
app.options('*', cors());
const RedisStore = connectRedis(session);
const client = redis.createClient();
app.use(session({
store: new RedisStore({ client: client }),
secret: xxxxx,
resave: false,
saveUninitialized: false,
cookie: {
maxAge: config.sessionMaxAge,
secure: false,
},
}))
app.use('/api/auth', authController);
app.listen(config.port, () => console.log(`Listening at http://localhost:${config.port}`));