AngularJS:无法使用适当的CORS标头发送POST请求

Jor*_*alo 5 javascript jquery node.js cors angularjs

我正在使用AngularJS创建一个Web应用程序.为了测试它,我使用angular-seed模板NodeJS服务器中运行应用程序.

在这个应用程序中,我需要通过POST请求向另一个主机发送JSON消息,并获得响应,因此,我正在使用CORS.

我的请求是通过实现使用AngularJS http服务的服务完成的(我需要$ http提供的抽象级别.所以,我不使用$ resource).

在这里,我的代码.请注意我修改$ httpProvider以告诉AngularJS使用适当的CORS头发送其请求的事实.

angular.module('myapp.services', []).

  // Enable AngularJS to send its requests with the appropriate CORS headers
  // globally for the whole app:
  config(['$httpProvider', function($httpProvider) {
          $httpProvider.defaults.useXDomain = true;

          /**
           * Just setting useXDomain to true is not enough. AJAX request are also
           * send with the X-Requested-With header, which indicate them as being
           * AJAX. Removing the header is necessary, so the server is not
           * rejecting the incoming request.
           **/
          delete $httpProvider.defaults.headers.common['X-Requested-With'];
      }
  ]).

  factory('myService', function($http) {
    return {
      getResponse: function() {
        var exampleCommand = JSON.stringify({"foo": "bar"});

        // This really doesn't make a difference
        /*
        var config = {headers: {
            'Access-Control-Allow-Origin':'*',
            'Access-Control-Allow-Headers': 'Content-Type, Content-Length, Accept',
            'Content-Type': 'application/json'
          }
        };
        */

        //return $http.post(REMOTE_HOST, exampleCommand, config).
        return $http.post(REMOTE_HOST, exampleCommand).
          success(function(data, status, headers, config) {
              console.log(data);
              return data;
          }).
          error(function (data, status, headers, config) {
            return {'error': status};
          });
      }
    }
  });
Run Code Online (Sandbox Code Playgroud)

问题是我无法使其发挥作用.我总是收到此错误消息:

跨源请求已阻止:同源策略禁止在REMOTE_HOST读取远程资源.这可以通过将资源移动到同一域或启用CORS来解决.

但是,如果我这样做一个简单的jQuery AJAX调用:

$.ajax(REMOTE_HOST,
{
    dataType: "json",
    type: "POST",
    data: exampleCommand,
    success: function(data) { console.log(data); },
    error: function(request, textStatus, errorThrown) { console.log("error " + textStatus + ": " + errorThrown);}
 });
Run Code Online (Sandbox Code Playgroud)

它工作正常.

所以,我的问题:

- 如何在NodeJS下运行的AngularJS中允许跨站点请求?

更新:感谢Dayan Moreno Leon的回复.

我的问题是我需要为我的服务器添加cors支持.我正在使用NodeJS http-server进行开发,使用lighttpd进行生产.

- 为什么简单的jQuery POST请求有效,但AngularJS POST请求不起作用?

我猜jQuery AJAX请求默认是跨域的.还不太确定.

提前谢谢了

Day*_*eon 4

CORS 不在客户端上处理,但在服务器中,您需要在 Angular 应用程序尝试 POST 的 Nodejs 应用程序上允许 CORS。如果您使用的是express,您可以尝试使用cors模块

https://www.npmjs.org/package/cors

其他情况下,您需要检查 options 方法并返回 200 作为响应

http://en.wikipedia.org/wiki/Cross-origin_resource_sharing