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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24083329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:09:55  来源:igfitidea点击:

AngularJS: Cannot send POST request with appropiate CORS headers

javascriptjquerynode.jsangularjscors

提问by Jorge Arévalo

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创建一个网络应用程序。为了测试它,我在NodeJS 服务器中运行该应用程序,使用angular-seed 模板

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-serverfor development and lighttpdfor 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-domainby default. Not really sure yet.

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

Many thanks in advance

提前谢谢了

采纳答案by Dayan Moreno Leon

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 不在客户端处理,但在服务器中,您需要在您的 angular 应用程序尝试 POST 的 nodejs 应用程序上允许 CORS。如果您使用 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

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

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

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

回答by shubhu

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

为什么简单的 jQuery POST 请求有效而 AngularJS POST 请求无效?

jQuery uses simple requestswhile AngularJS uses preflighted requests

jQuery 使用简单请求,而 AngularJS 使用预检请求

In your angular code you can add set Content-Typeto application/x-www-form-urlencodedand encode your data using $.param

在你的角度代码,你可以添加集Content-Typeapplication/x-www-form-urlencoded使用编码数据$.param