How to add CORS Configuration in Angular Controlle

2019-02-16 05:32发布

问题:

I have a Server which will Fetch data from Mongo and it will kick in json type

CORS PROBLEM

server.js /

/ server Side CORS  Code aded
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,DELETE');
    res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
    if ('OPTIONS' == req.method){
        return res.send(200);
    }
    next();
});

Guys Plz suppose the Link **Baseurl** as my menu API 

var baseurl="http://localhost:8000/menus";(for your Convenience)

   **baseurl**   which kicks a Json

Now my aim to request it by Angular controller($http):-

    'use strict'
    var app = angular.module('AngularApp', []);
    **/// Cors enabled Cliet side**
    app.config(['$httpProvider', function ($httpProvider) {
            // ...
               $httpProvider.defaults.useXDomain = true;
        $httpProvider.defaults.withCredentials = true;
        delete $httpProvider.defaults.headers.common["X-Requested-With"];
        $httpProvider.defaults.headers.common["Accept"] = "application/json";
        $httpProvider.defaults.headers.common["Content-Type"] = "application/json";
        }]);

**var baseurl="http://localhost:8000/menus";**
    app.controller("MenuController", function($scope, baseurl,$http) {

        $scope.menu= [];

        $http.get(baseurl).success(function(data) {


            $scope.menu=data;


        });
    });

... when i tested in Browsers

Firefox Returns CORS error:- Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at baseurl. This can be fixed by moving the resource to the same domain or enabling CORS. Chrome raising :- XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin localhost is therefore not allowed access.