【问题标题】:Sails/Angular Cross-Origin Request BlockedSails/Angular 跨域请求被阻止
【发布时间】:2015-04-24 03:15:10
【问题描述】:

我在 localhost:9000 上有一个 Angular 应用程序作为前端,并在 loclahost:1337 上作为后端运行

在 Angular 应用程序中,我这样做是为了查询服务器:

angular.module('webApp')
.controller('FoodCtrl', function($scope, $resource) {

    var Food = $resource('http://localhost:1337/food', {
        id: '@id'
    }, {
        update: {
            method: 'PUT'
        }   
    }); 

    $scope.food = new Food();
    $scope.foodList = Food.query();

    $scope.saveFood = function() {

        var method = $scope.food.id ? '$update' : '$save';

        $scope.food[method]({}, function() {

            $scope.food = new Food();
            $scope.foodList = Food.query();

            console.log("Saved!!");
        })
    };

行为有点奇怪。如果我去 Angular 应用程序并尝试从 Firefox 触发 saveFood 功能:

跨域请求被阻止:同源策略不允许读取 localhost:1337/food 上的远程资源。这可以通过将资源移动到同一域或启用 CORS 来解决。

与 Chrome 有点不同。有时我得到 CORS 错误,有时没有,有时服务器上的模型甚至更新了值......但页面显示“无法 POST/”

现在在我的风帆应用程序中,我启用了 CORS,如下所示: https://github.com/tarlepp/angular-sailsjs-boilerplate/blob/master/backend/config/cors.js#L71

编辑:当我检查请求的标头时,我看到 2 个帖子,一个在 localhost:1337/food 上,其中包含 Access-Control-Allow-Origin: localhost:9000,另一个在 localhost:9000/#/food没有得到 404

这是 chrome 控制台的示例输出:

2Navigated to http://localhost:9000/
(index):1 POST http://localhost:9000/ 404 (Not Found)
2Navigated to http://localhost:9000/
(index):1 POST http://localhost:9000/ 404 (Not Found)
2Navigated to http://localhost:9000/
food.js:33 Saved!!
(index):1 POST http://localhost:9000/ 404 (Not Found)
Navigated to http://localhost:9000/

所以一次它不发布,另一次发布。但我总是在页面上得到“无法发布/” 如果你想重现它,所有的代码和步骤都在这里: http://okamuuu.hatenablog.com/entry/2014/04/10/135240

【问题讨论】:

    标签: angularjs node.js model-view-controller cors sails.js


    【解决方案1】:

    Sails.js 为 config/cors 下的 CORS 提供配置。

    您可以在此处指定允许哪些外国主机请求您的数据。

    【讨论】:

      【解决方案2】:

      端口有一个冒号,它会被剥离,你需要转义它

      尝试使用单“\”或双“\”反斜杠

      http://localhost\:1337/
      

      http://localhost\\:1337/
      

      代码

      $resource('http://localhost\:1337/food', {
              id: '@id'
          }, {
              update: {
                  method: 'PUT'
              }   
          }); 
      

      【讨论】:

      【解决方案3】:

      尝试将其添加为 config/routes.js 中的第一条路由

      'OPTIONS /*': function(req, res) {return res.send(200);},
      

      Angular 运行一个预检 OPTIONS 请求来检查授权的内容。您需要响应此请求。

      【讨论】:

      • 检查您的控制台,看看您是否看到 OPTIONS 请求也被调用和响应。
      • 取决于...有时选项被接受有时是 404
      • 嗯,这听起来很奇怪。如果没有那行代码,OPTIONS 请求上的 404 错误就是您所期望的。为了让你间歇性地得到它,我认为这是一个更大的问题。我会先尝试使用 Postman 来消除或挑出客户作为问题?
      • 请注意,404 并不总是在选项中,大多数时候它在帖子上。我不知道邮递员我要去看看 thx
      • 如果邮递员与您的客户端浏览器一样,那么我建议发布您的路线和策略(以及任何其他自定义中间件)。
      猜你喜欢
      • 2018-10-07
      • 2019-02-22
      • 1970-01-01
      • 2022-02-16
      • 2023-03-03
      • 2016-05-19
      • 2021-06-26
      相关资源
      最近更新 更多