javascript - AngularJS 的跨域请求不起作用

标签 javascript angularjs

我需要使用 Angular 执行跨域请求,但出现错误

XMLHttpRequest cannot load http://machine_name_in_my_network:8082/GetAll. No

'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:53379' is therefore not allowed access. The response had HTTP status code 500.

我看到了here一个解决方案示例,但对我不起作用。

这是从我的本地主机到我网络中的一台机器的请求,应该返回一个 JSON。

代码片段

//Controller 
function crmContatosCtrl($scope, apiService) {
    apiService.get('/GetAll').then(function (data) {
       $scope.contatos = data;
    });

然后为我服务

function comWebApi_Service($http, $log) {
    return {
        get: function (url, data) {

            //return $http.jsonp(ApiURL + url)
            //    .success(function (data) {
            //        debugger;
            //    })
            //    .error(function (data) {
            //        debugger;
            //    });

            return $http.get(ApiURL + url, data).then(
                function (res) {                
                    return res.data;
                });
        },

    angular
        .module('app')
        .config(['$httpProvider', function($httpProvider) {
            $httpProvider.defaults.useXDomain = true;
            delete $httpProvider.defaults.headers.common['X-Requested-With'];
        }])
        .service('apiService', comWebApi_Service);

最佳答案

你需要在服务器上启用cors

例如全局初始化

    var cors = new EnableCorsAttribute("*", "*", "*");
    config.EnableCors(cors);

了解更多 here ...阅读部分 [EnableCors] 的范围规则

关于javascript - AngularJS 的跨域请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27175128/

相关文章:

javascript - Keyup 函数不传输下部 div 中的数据

javascript - Angular Controller : How are these magic methods working in this unit test?

javascript - 带有单选框的 ng-repeat 表的键盘控制

javascript - Angular.js - 在指令中设置 ng-pattern 时 ngModel 值未定义

javascript - 覆盖 JavaScript 会在 IE 中导致无限循环,但在 Firefox 中不会

javascript - 网络包 : Invalid configuration object/Invalid Module Entry

javascript - promise 何时被摧毁?

javascript - 如何使用 Angular 有条件地将资源包含在 <head> 中

javascript - AngularJS slider 范围值没有显示在上面?

css - 滑出抽屉在手机上 FPS 差