Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sails/Angular Cross-Origin Request Blocked

I have an angular app as frontend on localhost:9000 and sails as backend on loclahost:1337

In the angular app I do this to query the server:

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!!");
        })
    };

The behaviour is a bit strange. If I go to the angular app and try to trigger the saveFood function from Firefox:

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

From Chrome is a bit different. Sometimes I get the CORS error and sometimes not, sometimes the model on the server is even updated with the value... But the page shows "Cannot POST/"

Now in my sails app I have enabled CORS just like this: https://github.com/tarlepp/angular-sailsjs-boilerplate/blob/master/backend/config/cors.js#L71

edit: when I check the header of the request I see 2 post, one on localhost:1337/food which contains Access-Control-Allow-Origin: localhost:9000 and the other one to localhost:9000/#/food which don't and get 404

This is an exemple output from the chrome console:

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/

So one time it doesn't post it and the other it does. But I always get "Cannot POST /" on the page If you want to reproduce it all the code and steps are here: http://okamuuu.hatenablog.com/entry/2014/04/10/135240

like image 680
dkx22 Avatar asked Jun 23 '26 13:06

dkx22


1 Answers

Sails.js provides configuration for CORS under config/cors.

You can specify there which foreign hosts are allowed to request your data.

like image 93
Himmet Avsar Avatar answered Jun 26 '26 12:06

Himmet Avsar