1

I am Newbie to angular js. Here I am trying to call API from rails server with "http://localhost:3000/". I got error for

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin'

I have added 'CORS' chrome extension to fix it. Now the problem is my request is passing to localhost:3000 as [OPTIONS], and I want it as get request.

'use strict';

angular.module('dayton')
.service('foodCategoryService', ['$http', '$window', 'authService', 'Upload',
  function($http, $window, authService, Upload){
        var field = {};

      field.getFields = function (){
        console.log("---------foodCategoryService")
        return $http.get('http://localhost:3000/api/list_food_category',  {
          headers: {Authorization: authService.getToken()}
        })
        .then(function(response) {
          return response;
        }, function(x) {
          $scope.authError = 'Server Error';
        });
      };
        return field;
  }]);

ActionController::RoutingError (No route matches [OPTIONS] "/api/list_food_category"):

Any help is going to be appreciated

Shefalee Chaudhary
  • 582
  • 12
  • 28
  • CORS plugin only can't fix it. Your server needs to allow request for CORS. – Ved Dec 15 '16 at 06:25
  • You don't need a CORS extension, if you are making calls and hosting your frontend on the same host, ie `localhost` right? – M. Junaid Salaat Dec 15 '16 at 06:25
  • No, I am using two different servers here. http://localhost:8081/ is my current server and I am trying to send api call to http://localhost:3000/ – Shefalee Chaudhary Dec 15 '16 at 06:27
  • @Ved I have tried to add allow request for CORS. would you suggest me any link to refer ? I have tried with app.use(function (req, res, next) { .... but getting error for app and use function in express.js – Shefalee Chaudhary Dec 15 '16 at 06:31
  • 1
    check here: http://stackoverflow.com/questions/7067966/how-to-allow-cors – Ved Dec 15 '16 at 06:35

2 Answers2

0

modify your app config

angular.module('dayton').config(function($httpProvider){

    $httpProvider.defaults.headers.common = {};
    $httpProvider.defaults.headers.post = {};
    $httpProvider.defaults.headers.put = {};
    $httpProvider.defaults.headers.patch = {};
});
Azad
  • 5,144
  • 4
  • 28
  • 56
0

It is not your angular js side problem. You have to allow cross origin request at your server end

Abdullah
  • 909
  • 7
  • 3
  • For server side, I am using node.js . Can you please suggest which changes I need to do for that? – Shefalee Chaudhary Dec 15 '16 at 06:35
  • https://developer.mozilla.org/en-US/docs/Web/HTTP/Ac cess_control_CORS example code : app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); – Abdullah Dec 16 '16 at 04:45