Enabling CORS not working with Spotify Web API
1) You don't have to send Access-Control-* headers when making call from your client (ejs page).
2) The server needs to respond back with Access-Control-* headers to allow CORS. The server also needs to handle 'OPTIONS' request first. Normally, I do this without using the cors middleware like this:
// Enabling CORS
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "*");
if (req.method === "OPTIONS") {
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH");
return res.status(200).json({});
}
next();
});
It's not a good practice to use * and it will not be allowed in the case where browser needs to accept cookies. But you can use it now to test your api.
The above can also be achieved using cors middleware.
The below line:
app.use(cors())
should be added only once before the request is sent to any route/controller.
This ensures that the headers required to allow CORS are actually added for every response.
Update:
If you want to access the spotify page from your browser, it should be redirected from your client (ejs page). Get the necessary data from your server and use it to redirect from your client.
CORS redirection problem with Spotify API?
Edit : Not working
Did you try to add the Origin in the headers of the angular call ?
Something like that :
public login(): Observable<any> {
const url = backendURL + BackendEndpoints.Login;
const header = new HttpHeaders();
header.append('Origin', 'http://localhost:4200');
return this.http.get<any>(url, {withCredentials: true, headers: header});
}
Edit2 :
You can try to create the a link :
<a href="/login" #spotifyConnectLink></a>
Then you create a button to ask the user to click to connect :
<button (click)='handleCacheAndLaunchConnection()'>Connect To Spotify</button>
On your ts you create the handleCacheAndLaunchConnection function and you force the click on the a link with Viewchild :
@ViewChild('spotifyConnectLink') spotifyConnectLink: ElementRef;
handleCacheAndLaunchConnection() {
//Do the stuff you need for app and cache
let el: HTMLElement = this.spotifyConnectLink.nativeElement;
el.click();
}
Hope this work
CORS error when sending a request from my reactjs app to my express server, which redirects to Spotify's API
Step one to avoid CORS issues is to make sure your website on Spotify is 'localhost:4000'.
The redirect is most likely causing the concern. You don't want to use a redirect. You want Spotify to authenticate the user and then redirect them back to your website with a token.
I would suggest using passportJS, this is a much more secure way if you are new to handling tokens and such.
Create a strategy as such
const passport = require('passport');
const SpotifyStrategy = require('passport-spotify').Strategy;
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
passport.use(new SpotifyStrategy({
clientID: "c2b60e83cbdb4b5ba923140f0c32ac8f",
clientSecret: "d45b554801ab4333b89a36bdbf04fad7",
callbackURL: "http://localhost:4000/auth/spotify/callback"
},
function(accessToken, refreshToken, profile, done) {
return done(null, profile);
}
));
PassportJS Spotify Docs
const passport = require('passport');
require('./passport')
app.use(passport.initialize());
app.use(passport.session());
app.get('/auth/spotify',passport.authenticate('spotify'));
app.get('/auth/spotify/callback',passport.authenticate('spotify', { failureRedirect: '/auth/error' }),
function(req, res) {
res.redirect('/');
});
app.get('/logout', (req, res) => {
req.session = null;
req.logout();
res.redirect('/');
})
Related Topics
Is a JavaScript Array Index a String or an Integer
Dynamically Update Values of a Chartjs Chart
Split String Only on First Instance of Specified Character
How to Add a Key Prop to a React Fragment
Jqgrid - Maintain Check Box Selection State - Page Refresh/Redirect/Reload
How to Round a Number in JavaScript? .Tofixed() Returns a String
Element Not Visible Error (Not Able to Click an Element)
Destructuring and Rename Property
How to Redefine a JavaScript Class's Method
JavaScript - Return String Between Square Brackets
How to Implement Prepend and Append with Regular JavaScript
What Is Settimeout Doing When Set to 0 Milliseconds
What Is the List of Possible Values for Navigator.Platform as of Today
Chrome Extension: Port Error: Could Not Establish Connection. Receiving End Does Not Exist
What Are the Actual Uses of Es6 Weakmap
How to Intercept All Ajax Requests Made by Different Js Libraries