I am relatively new to RectJs and Node and I am trying to fetch some information from Spotify using their API. The Github repo that I got some code from had an HTML file along with the node file for authorization. The authorization and other stuff work fine when I use that HTML to click buttons and trigger calls but when I try to call the authorization endpoint for Spotify using my React server, it gives me this error:
Access to XMLHttpRequest at 'https://accounts.spotify.com/authorize?response_type=code&client_id=3054cb711c3c4fc48cff3458cdaddea2&scope=user-read-private%20user-read-email&redirect_uri=http%3A%2F%2Flocalhost%3A8888%2Fcallback&state=J9lrQajWgCnjJy0q' (redirected from 'http://localhost:8888/login') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
ReactJS server:
import React, {Component} from 'react';
import './Spotify.scss';
import axios from 'axios';
export default class First extends React.Component {
handlelogin(){
axios
.get('http://localhost:8888/login', {
headers: {
'Access-Control-Allow-Origin': '*',
}
})
.then()
.catch(err => {
console.error(err);
});
}
render(){
return(
<div className="container">
<div className="info">
<div className="logo"><p>Spotify</p></div>
<button className="btn" name="login" onClick= {() => this.handlelogin()}> Log-in to Spotify </button>
</div>
</div>
);
}
}
Node Server:
var express = require('express');
var request = require('request');
var cors = require('cors');
var querystring = require('querystring');
var cookieParser = require('cookie-parser');
var SpotifyWebApi = require('spotify-web-api-node');
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
var usersid='';
var stateKey = 'spotify_auth_state';
var client_id = '3054cb711c3c4fc48cff3458cdaddea2';
var client_secret = 'b43bf5c8fe0040829f0029ac301a5ea7';
var redirect_uri = 'http://localhost:8888/callback';
var spotifyApi = new SpotifyWebApi({
clientId: '3054cb711c3c4fc48cff3458cdaddea2',
clientSecret: 'b43bf5c8fe0040829f0029ac301a5ea7',
redirectUri: 'http://www.localhost:8888'
});
var generateRandomString = function(length) {
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
};
app.use(express.static(__dirname + '/public'))
.use(cors())
.use(cookieParser());
app.get('/login', function(req, res) {
console.log('ABCD');
var state = generateRandomString(16);
res.cookie(stateKey, state);
// your application requests authorization
var scope = 'user-read-private user-read-email';
res.redirect('https://accounts.spotify.com/authorize?' +
querystring.stringify({
response_type: 'code',
client_id: client_id,
scope: scope,
redirect_uri: redirect_uri,
state: state
}));
});
app.get('/callback', function(req, res) {
var code = req.query.code || null;
var state = req.query.state || null;
var storedState = req.cookies ? req.cookies[stateKey] : null;
if (state === null || state !== storedState) {
res.redirect('/#' +
querystring.stringify({
error: 'state_mismatch'
}));
} else {
res.clearCookie(stateKey);
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: redirect_uri,
grant_type: 'authorization_code'
},
headers: {
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
},
json: true
};
request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {
var access_token = body.access_token,
refresh_token = body.refresh_token;
tokenuse = access_token;
spotifyApi.setAccessToken(access_token);
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
// use the access token to access the Spotify Web API
request.get(options, function(error, response, body) {
console.log(body);
userid = body.id;
usersid = body.id;
});
// we can also pass the token to the browser to make requests from there
res.redirect('/#' +
querystring.stringify({
access_token: access_token,
refresh_token: refresh_token
}));
} else {
res.redirect('/#' +
querystring.stringify({
error: 'invalid_token'
}));
}
});
}
});
app.get('/refresh_token', function(req, res) {
var refresh_token = req.query.refresh_token;
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
headers: { 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')) },
form: {
grant_type: 'refresh_token',
refresh_token: refresh_token
},
json: true
};
request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {
var access_token = body.access_token;
token = body.access_token;
res.send({
'access_token': access_token
});
}
});
});
console.log('Listening on 8888');
app.listen(8888);```