【问题标题】:CORS problems no 'access control allow origin header' is present on the requested resourceCORS 问题 请求的资源上不存在“访问控制允许来源标头”
【发布时间】:2016-03-15 09:06:51
【问题描述】:

这就是我想要做的:

function fetch() {
              $http.get("http://www.myapifilms.com/imdb/top")
                .success(function(response) {
                    console.log(response);
                  $scope.details = response;
                });
            };

我收到的错误如下:

XMLHttpRequest 无法加载 http://www.myapifilms.com/imdb/top。请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'http://localhost:3000' 因此不允许访问。

我已经对这个问题或 CORS 进行了相当多的查找,但似乎仍然无法意识到我必须添加什么以及在哪个文件中。

【问题讨论】:

  • 在这种情况下使用 JSONP。
  • 我尝试了以下方法:function fetch() { $http.jsonp("http://www.myapifilms.com/imdb/top") .success(function(response) { $scope.details = response; console.log(response); console.log(details); }); }; 但似乎无法获取控制台日志并且详细信息未填满?

标签: javascript angularjs api cors


【解决方案1】:

这意味着http://www.myapifilms.com 不允许“localhost”源访问其数据。

我可以推荐两种解决方案:

【讨论】:

  • 我也计划在 heroku 上托管应用程序,如果可以的话,我还计划在 heroku 上托管数据库。它会接受这些网址吗?另外,如何使用 http-server 对其进行测试?那我在我的代码中添加什么?
  • 在 heroku 上托管您的应用程序可能会起作用,因为它会为您提供一个 URL 。在apifilms的后面,人们写了一行说允许来自“网站URL”的任何连接,但不允许来自任何来源..我猜它是出于安全目的。 http-server 再次取决于他们的权限.. 测试只需下载 chrome 插件就可以了
  • 我现在已经使用 $http.jsonp() 但我似乎仍然无法让它工作......如果你有兴趣:stackoverflow.com/questions/34191130/…
【解决方案2】:

使用这个插件: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

//make headers for service
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('appCurrentVersionNumber', AppConstant.APP_VERSION);
headers.append('WebServiceIdentifier', AppStorage.getItem('webserviceidentifier'));
this.headers = {headers}; this.http.post(API_URL + 'checkInVan', JSON.stringify(userData), this.headers).map(res => res.json());

【讨论】:

    【解决方案3】:

    要使此请求成功,来自 myapifilms.com 的响应需要设置正确的标头。您应该做的是通过您自己的服务器路由您的请求。但是,您可以使用 browser extension

    绕过它进行测试

    Explained in detail here.

    【讨论】:

    • 嗯,是的,这可能是因为它不允许本地主机连接,将我的应用程序托管在 heroku 上使其工作,因为它不再是本地主机了。
    猜你喜欢
    • 2020-09-17
    • 2021-09-07
    • 2017-11-27
    • 2018-11-08
    • 2017-11-11
    • 2020-09-25
    • 2013-12-13
    • 2016-12-09
    • 2019-02-09
    相关资源
    最近更新 更多