javascript - AngularJS:请求的资源上不存在 "Access-Control-Allow-Origin" header

标签 javascript html angularjs xmlhttprequest cors

我正在编写我的 webApp,我正在使用 AngularJS。在这个应用程序中,我创建了一个名为 script.js 的文件,我报告了这段代码:

var modulo = angular.module('progetto', ['ngRoute']);

    // configure our routes
    modulo.config(function ($routeProvider, $httpProvider) {
        $routeProvider

            // route for the home page
            .when('/', {
                templateUrl: 'listaFilm.html',
                controller: 'listaController'
            })

            // route for the description page
            .when('/:phoneName', {
                templateUrl: 'description.html',
                controller: 'descriptionController'
            });


            $httpProvider.defaults.headers.common['Access-Control-Allow-Origin'] = '*';

    });


    modulo.controller('listaController', function ($scope, $http) {
        $http.get('https://api.getevents.co/event?&lat=41.904196&lng=12.465974').success(function (data) {
            $scope.names = data;
            }).
            error(function (data, status) {
                $scope.names = "Request failed";
            });
    });

使用此代码,我按照 RESTful 原则调用 API。当我运行代码时,我遇到了这个问题:

XMLHttpRequest cannot load https://api.getevents.co No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8383' is therefore not allowed access.

在网上阅读后我了解到我遇到了一个名为 CORS 的问题...我已经尝试了几种提出的解决方案,但我没有解决问题。
我该如何解决这个问题?
我必须添加什么代码才能修复它?

最佳答案

这是服务器端问题。您不需要为 cors 添加任何 Angular 标题。 您需要在服务器端添加 header :

Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *

前两个答案在这里:How to enable CORS in AngularJs

关于javascript - AngularJS:请求的资源上不存在 "Access-Control-Allow-Origin" header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29547003/

相关文章:

javascript - CSS 技能栏响应式

jquery - 如果 <div> 位于容器 <div> 的底部,我如何使它向上生长?

javascript - 使用 ajax 时如何保护 Elasticsearch

javascript - 如何将 JSON 数据传递给代码隐藏方法(而不是 Webmethod)?

javascript - 无法要求 jqueryui

javascript - 如何使用ajax获取可编辑Sencha网格4.2中的编辑值以进行编辑?

javascript - 为什么我在此函数定义中得到 “Error 25: Expected: ;”?

javascript - 我可以在创建新的 Web Workers 对象时将参数传递给 .js 函数吗?

angularjs - 在 AngularJS 中如何为 Angular-Material 中的 md-tabs 启用滑动功能?

javascript - 使用在 AngularJS 中动态构建的表中的输入验证行