Http REST调用问题POST上没有'Access-Control-Allow-Origin'

时间:2014-06-13 19:17:45

标签: http rest cors

我无法让Angular $ http与远程REST服务进行通信。我也尝试过Restangular和$ resource。问题似乎与底层的$ http服务和CORS限制有关。我想我只需要让我的标题正确。我是否还需要调整我的服务器配置?

我收到以下错误:

XMLHttpRequest cannot load http://www.EXAMPLE-DOMAIN.com/api/v2/users/sign_in. No 'Access-Control-    Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. 

我对此进行了很多研究。目前我已经尝试在配置我的app模块时设置$ httpProvider标题并使用$ http标头播放。以下是我目前的一些代码。

我的服务

app.service('Auth', function($http) {

        var headers = {
            'Access-Control-Allow-Origin' : '*',
            'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS, PUT',
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        };

        return $http({
            method: "POST",
            headers: headers,
      url: 'http://www.EXAMPLE-DOMAINcom/api/v2/users/sign_in',
            data: {"email":"my@email.com","password":"secret"}
    }).success(function(result) {
                console.log("Auth.signin.success!")
                console.log(result);
    }).error(function(data, status, headers, config) {
                console.log("Auth.signin.error!")
        console.log(data);
        console.log(status);
        console.log(headers);
        console.log(config);
    });

});

App Config

var app = angular.module('starter', ['ionic', 'app.controllers', $httpProvider])

    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        $httpProvider.defaults.headers.common = 'Content-Type: application/json';
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }
])

1 个答案:

答案 0 :(得分:3)

如果您控制服务器,则可能需要在那里设置所需的标头。根据哪个服务器,这可能有所帮助:http://enable-cors.org/server.html