2

I am trying to make cross domain call from angular.js module to nodejs + express server, and I am getting unauthorized error, or headers errors: I followed the Cors configuration and still I am having an issue.

Angular.js code:

methods.getWelcomeApps = function (onSuccess, onError) {
        function makeBasicAuth(user, password) {
            var tok = user + ':' + password;
            var hash = btoa(tok);  // Base64 encoding
            return "Basic " + hash;
        }

        var auth = makeBasicAuth(config.API.AppsList.username, config.API.AppsList.password);
        $http.defaults.useXDomain = true;
        $http({method: 'GET', url: config.API.AppsList.url,  headers: {'Authorization': auth}})
            .success(onSuccess)
            .error(onError);
        };

    return methods;
});

And the node.js code:

allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With');
res.header('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === 'OPTIONS') {
  return res.send(200);
}
return next();
};

Do I miss something?

thx.

4

1 回答 1

3

我认为这是不必要的:

res.header('Access-Control-Allow-Headers', 'Content-Type');

这已经足够了

var allowCrossDomain = function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
};

也许你有兴趣:

完整的工作代码- angularjs 客户端服务和 nodejs 服务器服务:

客户端(angularjs v1.0.8)

motoads/app/js/services.js

var motoAdsServices = angular.module('motoAdsServices', ['ngResource']);

motoAdsServices.factory('Brand', ['$resource', function($resource) {
    return $resource('http://localhost\\:3000/api/:id', {}, {
      query: {
        method: 'GET',
        params: {
          id: 'brands'
        },
        isArray: true
      }
    });
  }]);

服务器(nodejs + express)

motoads/server/server.js

var express = require('express');
var path = require('path');
var http = require('http');
var brands = require('./routes/brands');

var app = express();

var allowCrossDomain = function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
};

app.configure(function() {
  app.set('port', process.env.PORT || 3000);
  app.use(express.logger('dev'));  /* 'default', 'short', 'tiny', 'dev' */
  app.use(express.bodyParser()),
          app.use(allowCrossDomain);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.get('/api/brands', brands.findAll);

http.createServer(app).listen(app.get('port'), function() {
  console.log("Express server listening on port " + app.get('port'));
});

motoads/server/routes/brands.js

exports.findAll = function(req, res) {
  var fs = require('fs');
  var file = './server/data/brands.json';

  fs.readFile(file, 'utf8', function(err, data) {
    if (err) {
      throw err;
    }
    res.send(JSON.parse(data));
  });
};

motoads/server/data/brands.json

[
  {"name": "Audi", "models": [{"name": "A1"}, {"name": "A3"}, {"name": "A4"}]},
  {"name": "BMW", "models": [{"name": "Series 3"}, {"name": "Series 5"}, {"name": "Series 7"}]},
  {"name": "Citroen", "models": [{"name": "C1"}, {"name": "C2"}, {"name": "C3"}]},
  {"name": "Dacia", "models": [{"name": "Duster"}, {"name": "Logan"}, {"name": "Sandero"}]}
]
于 2013-11-13T18:28:07.307 回答