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.

2
  • And the specific errors are...? Commented Nov 13, 2013 at 17:02
  • Don't you need to allow OPTIONS too? Commented Nov 13, 2013 at 17:10

1 Answer 1

3

I think that it is unnecessary:

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

This is enough:

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

Maybe you are interested:

My complete working code - angularjs client service and nodejs server service:

Client (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
      }
    });
  }]);

Server (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"}]}
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.