如何在Angular Controller中添加CORS配置?

时间:2015-02-23 15:55:31

标签: angularjs cors

我有一个服务器,它将从Mongo获取数据,它将启用json类型

CORS问题

  

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”; (为了您的方便)

   **baseurl**   which kicks a Json

现在我的目标是通过Angular控制器($ 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;


        });
    });

...当我在浏览器中测试时

Firefox返回CORS错误: - 跨源请求已阻止:同源策略禁止在 baseurl 读取远程资源。这可以通过将资源移动到同一域或启用CORS来解决。 Chrome提升: - XMLHttpRequest无法加载。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许Origin localhost访问。

0 个答案:

没有答案