Angular:' Access-Control-Allow-Origin'标头出现在请求的资源上

时间:2015-06-13 21:56:51

标签: angularjs heroku cross-domain ionic-framework

我已经阅读了很多相同或类似的问题,几乎所有答案都是配置服务器。 我的客户端应用为Angular.js "ionic",我的服务器应用为node.js,部署在Heroku上。 这是我的服务器配置:

// 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();
})

注意:当我在本地运行服务器时,我的客户端通常与服务器通信

我的客户端应用无法发出任何http请求并收到此错误:

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.

这是请求标题:

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 个答案:

答案 0 :(得分:0)

很抱歉,如果这是一个愚蠢的错误,但也许对我这样的初学者有用。 我检查了我的服务器应用日志heroku logs并找到了此

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

并且因为heroku将端口分配给应用程序,所以我如何修复此问题: 从:

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

要:

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