Angular: 'Access-Control-Allow-Origin' header is present on the requested resource

1k views Asked by At

I've read alot of the same or similar questions and almost all the answers is to configure the server. My client app is Angular.js "ionic" my server app is node.js and deployed on Heroku. here is my server configuration:

// set up CORS resource sharing
app.use(function(req, res, next){
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    res.header('Access-Control-Allow-Credentials', true);
    next();
})

note: my client were normally communicate with the server when i run the server locally

my client app fail to make any http request and am getting this error:

XMLHttpRequest cannot load https://myheroku.herokuapp.com/api/x. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 503.

Here is the request header:

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,ar;q=0.6,fi;q=0.4,it;q=0.2,en-GB;q=0.2,en-CA;q=0.2
Access-Control-Request-Headers:accept, authorization
Access-Control-Request-Method:GET
Connection:keep-alive
Host:myheroku.herokuapp.com
Origin:http://localhost:8100
Referer:http://localhost:8100/
1

There are 1 answers

0
Ahmad Elmoualem On

Am sorry if it's a silly mistake but maybe it will be useful for beginners like me. i checked my server app logs heroku logs and found this

heroku process failed to bind to $PORT within 60 seconds of launch

and since heroku assign the port to the app this how i fixed this issue: From:

var server = app.listen(3000, function(){
    console.log('App listeining on', server.address().port);
})

To:

var server = app.listen(process.env.PORT || 5000, function(){
    console.log('App listeining on', server.address().port);
})