2

A website is doing a XMLHttpRequest to my node app, but they are getting the following error:

XMLHttpRequest cannot load http://[MY IP]/start. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.[THEIR WEBSITE].com' is therefore not allowed access. The response had HTTP status code 504.

This is their XMLHttpRequest request:

var xhr = typeof XMLHttpRequest === "undefined" ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest; 
xhr.open("POST", 'http://[MY IP]/myapp', true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(data));

This is the code in the node app (the ... represents irrelevant code):

...
var cors = require('cors')
...
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');
  res.header('Access-Control-Allow-Methods', 'GET,POST');
  next();
});

app.post('/myapp', function (req, res) {
  var data = req.body;
  console.log(data);
  res.status(200);
});

Do you have any idea why this isn't working?

Thanks for your advice.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Tom Brock
  • 920
  • 7
  • 29

2 Answers2

1

I am the person who created this question.

I figured out the answer.

If a XMLHttpRequest open request is set to asynchronous (third parameter set to 'true'), the node app must send a response. A status code is not enough. You must provide some sort of response. Otherwise you get a 504 timeout error.

EDIT: You can use res.sendStatus(200). My error was I was just doing res.status(200).

Tom Brock
  • 920
  • 7
  • 29
0

Try adding OPTIONS as one of the methods allowed.

Basically replace res.header('Access-Control-Allow-Methods', 'GET,POST'); with res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST');

limbuster
  • 71
  • 1
  • 5