angularjs – 如何在API和角度客户端之间启用CORS

我们一直试图建立CORS几天没有成功.因此,非常感谢知道如何一劳永逸地完成这项工作.

我们想要做的是:

API服务器(当然只是服务器的一部分):

 // Config
 app.configure(function () {
   app.use(bodyParser.urlencoded({ extended: false }))
   app.use(bodyParser.json())    
   app.use(express.methodOverride());
   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();
   });
   app.use(express.static(path.join(application_root, "public")));
   app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
   app.use(app.router);
 });

角度app的服务器(也只是设置的一部分):

 server.use(gzippo.staticGzip(__dirname + '/public'));
 server.set('view engine', 'ejs');

 // Environment
 var ENV = process.argv[2] || 'dev'; // prod or dev
 var port = process.env.PORT || 8080;

 // Single Page App (this route handles all other requests (catchall))
 server.all('/*', function(req, res, next) {
   res.set('Content-Type', 'text/html');
   res.render('index', includeFiles); // looks by default in views
 });

角度配置:

 app.config(['$locationProvider', '$httpProvider', '$urlRouterProvider', '$stateProvider',
    function($locationProvider, $httpProvider, $urlRouterProvider, $stateProvider) {

       ... Other stuff ...

       // enable CORS
       $httpProvider.defaults.useXDomain = true;
       delete $httpProvider.defaults.headers.common['X-Requested-With'];

       ...

    }
 ])

目前,当我们从角度请求时:

 $http.post('http://<ip-address>:8889/signin', {email: 'mike@gmail.com', pass: '1234abcd'})
 .success(function(data) {
   console.log(data);
 });

我们得到以下错误(在Firefox上):

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://<ip-address>/signin. (Reason: CORS preflight channel did not succeed).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://<ip-address>:8889/signin. (Reason: CORS request failed).

最佳答案 经过一些试验和错误后,我们使用了npm-module
cors,事情很顺利.

编辑API服务器:

// Config
app.configure(function () {
  app.use(bodyParser.urlencoded({ extended: false }))
  app.use(bodyParser.json())    
  app.use(express.methodOverride());
  app.use(cors());    // this was included
  app.use(express.static(path.join(application_root, "public")));
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  app.use(app.router);
});

角度配置:

app.config(['$locationProvider', '$httpProvider', '$urlRouterProvider', '$stateProvider',
   function($locationProvider, $httpProvider, $urlRouterProvider, $stateProvider) {

      ... Other stuff ...

      // deleted these rows, since they are unnecessary
      // $httpProvider.defaults.useXDomain = true;
      // delete $httpProvider.defaults.headers.common['X-Requested-With'];

      ...

   }
])

就是这样!希望它可以在将来帮助某人.

点赞