【问题标题】:POST issue in Angular JSAngular JS 中的 POST 问题
【发布时间】:2015-03-14 16:24:04
【问题描述】:

我在 Node js 中运行我的前端,在 Jetty 中运行后端。我正在尝试使用 Angular JS 从前端发布数据,但它对我不起作用。谁能建议可能是什么问题? 节点 Js 运行在 3000 端口,码头运行在 9011。 这是代码sn-p:

var app = angular.module("loginapp", []);

        app.controller("loginctrl", function($scope,$http) {
        app.config(['$sceDelegateProvider', function($sceDelegateProvider) {
            $sceDelegateProvider.resourceUrlWhitelist(['self', 'http://localhost:9011/**']);
             }]);

                $scope.login = function(e){
                    console.log('clicked login...');
                    e.preventDefault();                 

                    $http({
                              url: "http://localhost:9011/test/dummy/doStuff1",
                              method: "POST",
                              data : {username: $scope.userName, password: $scope.password},
                              headers: { 'Content-Type': 'application/json' },
                              withCredentials: false,
                              }).success(function (data, status, headers, config) {
                                    console.log('status',status);
                                    console.log('data',status);
                                    console.log('headers',status);
                            }); 

                }

        });

在浏览器控制台中显示:

POST http://localhost:9011/test/dummy/doStuff1 
(index):1 XMLHttpRequest cannot load http://localhost:9011/test/dummy/doStuff1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 500.

我不确定是什么导致了问题,有人可以帮我解决这个问题吗?

【问题讨论】:

  • 什么不起作用?你能指定吗?
  • POST 无法调用后端模块。我不确定是什么导致了问题。请您帮我确定原因。

标签: angularjs node.js express http-post angular-ui


【解决方案1】:

如果您在 node(localhost:3000) 上托管 Angular 应用程序并尝试向 jetty(localhost:9011) 发出 ajax 请求,您将遇到 CORS(http://enable-cors.org/) 问题。默认情况下,浏览器不会让您向其他域发出请求。您需要在服务器和 Angular 应用中启用 CORS。

服务器端显然取决于您使用的框架。使用 Jersey 的示例:http://blog.usul.org/cors-compliant-rest-api-with-jersey-and-containerresponsefilter/

然后在 Angular 中启用 CORS(在您的情况下这可能不是必需的......如果您从不同的域加载模板,则需要它):

//Allow CORS requests to these urls:
$sceDelegateProvider.resourceUrlWhitelist([
   'self',
   'http://localhost:9011/**'
]);

【讨论】:

  • 我按照你的建议做了,但还是不行。我已经用你建议的配置更新了问题。你能建议我缺少什么吗?
  • 你用什么做后端?您是否在后端启用了 CORS?
  • 我在后端的 Jetty 中运行 REST 服务。我已经按照您在后端的建议启用了容器响应过滤器。但是后端无法接收请求。我看到过滤器被调用,但我试图调用的方法没有发生。你能告诉我我是什么吗失踪了吗?
  • 我已经编辑了这个问题。问题仍然存在,但错误消息有所不同。你能告诉我可能是什么问题吗?
  • 看起来 CORS 没有在后端正确设置。该消息告诉您设置 Access-Control-Allow-Origin 标头。确保将其设置为您请求的域(localhost:3000),并且您应该为 OPTIONS 请求启用它,因为当它不是一个简单的请求时,浏览器会执行预检(OPTIONS)请求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-07
  • 2015-04-02
  • 1970-01-01
  • 2015-09-15
  • 1970-01-01
  • 2019-04-02
  • 2014-09-02
相关资源
最近更新 更多