5

I am new to node.js and got stuck on cors problem. I am sending client ajax get request from one express server to another, but at least I am not able to get response from app.all('*', function(req, res, next){console.log("request: "+req)}) GET request looks something like:

$.ajax({
    type: 'GET',
    url: 'http://localhost:8082/request'
});

I was also setting headers in ajax with:

'beforeSend : function(xhr) {
    xhr.setRequestHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
    xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
    xhr.setRequestHeader('Access-Control-Max-Age', '1000');
    xhr.setRequestHeader('Authorization', '*')},

...or setting cors module in node.js:

var cors = require('cors');
var app = express();
app.use(cors());
app.options('*',cors(),function(){
console.log("preflight")
});

In both firefox and chrome, I received no response (in chrome I got net::ERR_CONNECTION_REFUSED ) When running node servers locally on my PC, everything works. Also curl command works fine. Is there a chance, this is a problem with hosting/ports or am I still missing something?

Eidam
  • 97
  • 3
  • 6
  • possible duplicate of [How to allow CORS in Express/NodeJS?](http://stackoverflow.com/questions/7067966/how-to-allow-cors-in-express-nodejs) – Ray Nicholus Feb 26 '14 at 15:16

2 Answers2

4

You don't need to set the CORS headers on your $ajax call, as those headers are required by the browser in the HTTP Response header.

For cross domain AJAX, make sure you set the crossDomain flag on the $ajax option:

$.ajax({
  url: url,
  type: 'POST',
  data: payload,
  dataType: 'json',
  crossDomain: true
})

A clean way to handle CORS requests in your express endpoints would be to create a middleware that you add to express routes that respond to cross origin requests:

cors.js

module.exports = 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', 'Content-Type');  
  next();
};

Then make sure you add the middleware to the express endpoint:

app.post(url, cors, function(req, res) {
});
brryant
  • 41
  • 3
  • 3
    okey, i finally realised, that my problem was in setting url adresses of server. I replaced all my "localhost" with real domain name, set cors module in node.js and everything worked. Thank you once again for your time and ideas. – Eidam Feb 28 '14 at 23:39
1

I had same issue and solved with this:

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();
});
bmavus
  • 892
  • 1
  • 7
  • 21