Reputation: 63
My web application is using Angular 12 for the front end and Node.js 12.16.0 in the backend w/ Express.js. I am trying to develop a web application allowing the user to login with their Spotify API but I am having a lot of trouble with CORS even after looking up a bunch of posts. From the front end, my code is is just calling my /login
endpoint using HttpClient.
public login(): Observable<any> {
const url = backendURL + BackendEndpoints.Login;
return this.http.get<any>(url, {withCredentials: true});
}
From the backend, my endpoint setup looks like this with the appropriate variables filled in which should redirect my front end webpage to the Spotify login page.
router.get("/login", (req, res) => {
var state = generateRandomString(16);
var scope = 'user-read-email playlist-read-private'
res.redirect('https://accounts.spotify.com/authorize?' +
querystring.stringify({
response_type: 'code',
client_id: CLIENT_ID,
scope: scope,
redirect_uri: REDIRECT_URI,
state: state,
show_dialog: true
}));
});
I am also using the cors package as well in my middleware.
this.expressApp.use(cors({origin: 'http://localhost:4200', credentials: true}));
My front end does not redirect and instead gets this CORS error.
Cross-origin redirection to https://accounts.spotify.com/login?continue=https%3A%2F%2Faccounts.spotify.com%2Fauthorize%3Fscope%3Duser-read-email%2Bplaylist-read-private%26response_type%3Dcode%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A4200%252Fjoin%26state%3DjOZBRfRFxNi3auk6%26client_id%3D7e37838f2aa3449da5ee2b592a1a185e%26show_dialog%3Dtrue denied by Cross-Origin Resource Sharing policy: Origin null is not allowed by Access-Control-Allow-Origin.
Why am I getting CORS errors still? If possible, I'd like to just configure my backend instead of making a proxy server.
Upvotes: 2
Views: 1207
Reputation: 53
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
Upvotes: 1