AngularJS:不能发送带有批准CORS标题的POST请求

时间:2022-08-22 17:46:27

I'm creating a web app using AngularJS. To test it, I'm running the app in a NodeJS server, using angular-seed template.

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

In this app, I need to send a JSON message to another host, via POST request, and get the response, so, I'm using CORS.

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

My request is done by implementing a service that uses AngularJS http service (I need the level of abstraction that $http provides. So, I don't use $resource).

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

Here, my code. Please pay attention to the fact that I modify $httpProvider to tell AngularJS to send its requests with the appropriate CORS headers.

在这里,我的代码。请注意,我修改了$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};
          });
      }
    }
  });

The problem is I can't make it work. I always get this error message:

问题是我做不到。我总是收到这样的错误信息:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at REMOTE_HOST. This can be fixed by moving the resource to the same domain or enabling CORS.

跨源请求被阻塞:同源策略不允许在REMOTE_HOST读取远程资源。这可以通过将资源移动到相同的域或启用CORS来修复。

But if I do a simple jQuery AJAX call like this:

但是如果我做一个简单的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);}
 });

It works fine.

它将正常工作。

So, my questions:

所以,我的问题:

- How do I allow cross-site requests in an AngularJS running under NodeJS?

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

UPDATE: Thanks to Dayan Moreno Leon's response.

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

My problem is I need to add cors support to my server. I'm using NodeJS http-server for development and lighttpd for production.

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

- Why does the simple jQuery POST request work but AngularJS POST request doesn't?

-为什么简单的jQuery POST请求可以工作,而AngularJS POST请求不能工作?

I guess jQuery AJAX requests are cross-domain by default. Not really sure yet.

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

Many thanks in advance

提前感谢

2 个解决方案

#1


4  

CORS is not handled on the client but in the server you need to allow CORS on your nodejs app where your angular app is trying to POST. you can try using cors module if you are using express

CORS不是在客户端处理的,但是在服务器端,你需要允许CORS出现在你的nodejs应用中,在那里你的角应用正在尝试发布。如果使用express,可以尝试使用cors模块

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

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

other whise you need to check for the options method and return 200 as a response

其他需要检查选项方法并返回200作为响应

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

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

#2


3  

Why does the simple jQuery POST request work but AngularJS POST request doesn't?

为什么简单的jQuery POST请求可以工作,而AngularJS POST请求不能工作?

jQuery uses simple requests while AngularJS uses preflighted requests

jQuery使用简单请求,AngularJS使用预置请求

In your angular code you can add set Content-Type to application/x-www-form-urlencoded and encode your data using $.param

在您的角度代码中,您可以向应用程序/x-www-form- urlencoding添加set Content-Type,并使用$.param对数据进行编码

#1


4  

CORS is not handled on the client but in the server you need to allow CORS on your nodejs app where your angular app is trying to POST. you can try using cors module if you are using express

CORS不是在客户端处理的,但是在服务器端,你需要允许CORS出现在你的nodejs应用中,在那里你的角应用正在尝试发布。如果使用express,可以尝试使用cors模块

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

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

other whise you need to check for the options method and return 200 as a response

其他需要检查选项方法并返回200作为响应

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

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

#2


3  

Why does the simple jQuery POST request work but AngularJS POST request doesn't?

为什么简单的jQuery POST请求可以工作,而AngularJS POST请求不能工作?

jQuery uses simple requests while AngularJS uses preflighted requests

jQuery使用简单请求,AngularJS使用预置请求

In your angular code you can add set Content-Type to application/x-www-form-urlencoded and encode your data using $.param

在您的角度代码中,您可以向应用程序/x-www-form- urlencoding添加set Content-Type,并使用$.param对数据进行编码