【问题标题】:Angular: 'Access-Control-Allow-Origin' header is present on the requested resourceAngular:请求的资源上存在“Access-Control-Allow-Origin”标头
【发布时间】:2015-08-29 16:42:53
【问题描述】:

我已经阅读了很多相同或相似的问题,几乎所有的答案都是配置服务器。 我的客户端应用程序是 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/

【问题讨论】:

  • app.use() 是在 app.method('/api/x', ...) 之前还是之后?应该是之前。
  • 是的,当然,正如我提到的,它在本地运行良好。
  • 好吧,在本地它不应该需要 CORS,除非它们在不同的端口上。你能分享一下 HTTP 请求标头是什么吗?
  • 他们在不同的端口上运行,并且将请求标头添加到问题中
  • 方法是什么?是 GET 吗?

标签: angularjs heroku cross-domain ionic-framework


【解决方案1】:

很抱歉,如果这是一个愚蠢的错误,但它可能对像我这样的初学者有用。 我检查了我的服务器应用程序日志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);
})

【讨论】:

    猜你喜欢
    • 2020-07-10
    • 2016-06-30
    • 2016-10-08
    • 2018-10-31
    • 2019-07-21
    • 2016-08-17
    相关资源
    最近更新 更多