samedi 14 février 2015

Cors issue between rest api application server(express) and Angulars js application while running on different ports


Our app is built on decoupled MEAN stack architecture. I am trying to make successful request from my Angular front end to our backend. The backend definitely returns JSON. But every time I make a request from the frontend to the backend I get:



XMLHttpRequest cannot load http://localhost:9000/recipes/175169. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.


I have the following setup on the backend to accept cross origin requests:



app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
res.header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");

next();
});


The request being made from the frontend is:



recipe.controller('RecipeController', function($scope, $http) {
$scope.loadRecipe = function() {
$http({
url: 'http://localhost:9000/recipes/175169',
method: 'get',
headers: { 'Content-type': 'application/json' }
}).success(function(data) {
console.log(data);
}).error(function(data) {
console.log('Error: ' + data)
})
}


If I run the following to disable chrome, the request will work, but that doesn't seem like a real solution so much as a jenky work around.



open /Applications/Google\ Chrome.app--args --disable-web-security


This is my first StackOverflow post, and I am relatively new to Express and the MEAN stack, so I apologize if the solution is obvious. I have done quite a bit of research, and none of the solutions, I've found have fixed the problem.





Aucun commentaire:

Enregistrer un commentaire