0

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}`));
Joshua Dunn
  • 71
  • 1
  • 6
  • Did you require cors from npm in app.js? https://www.npmjs.com/package/cors. Also remove the s off https so its http, could solve the issue. Although Make sure you are using app.use(cors). – JS_noob Apr 22 '20 at 21:27
  • @JS_noob I've edited to show my index.ts – Joshua Dunn Apr 22 '20 at 21:29
  • Use HayProxy plugin i hope it may help you https://github.com/RoboMx/hayproxy – Aware Fun Apr 22 '20 at 21:30
  • 1
    The redirect is sending the browser to the URL instead of making the request from the server. CORS has to do with the browser + the spotify server, has nothing to do with your own servers. I think you want to be sending an http request from Node rather than redirecting the XMLHttpRequest – Dan Apr 22 '20 at 22:33
  • @Dan How should I alter the code to rectify this? – Joshua Dunn Apr 22 '20 at 22:37
  • 1
    I looked at their site and I see where you got that code. In that example, I'm pretty sure they intend for your browser to hit your server's `/login` route directly, not through an ajax request. Maybe they have a different process for ajax authorization. – Dan Apr 22 '20 at 22:52
  • 1
    @Dan If I use a link with href='...api/auth/login' my callback is hit, which is progress, but the state key I set in the cookies is always undefined there. Still, better than before so thanks! – Joshua Dunn Apr 22 '20 at 23:20
  • https://github.com/spotify/web-api-auth-examples/blob/master/authorization_code/app.js – Dan Apr 23 '20 at 00:29

0 Answers0