0

I have HTML/JS page with a ajax call to a node.js endpoint.

Talking to the endpoint is a success, however my Ajax errors out. Any Ideas?

My JS:

$.ajax({

  url: 'http://localhost:1234/test',
  type: 'POST',
  data: {
    "test": "1"
  },
  success: function (data) {
    alert("success");
  },
  error: function (request, error) {
    alert(JSON.stringify(request));
  }
});

My Node.js Endpoint:

  app.post('/test', function (req, res) {
    console.log(req.body.test);
    res.setHeader('Content-Type', 'application/json');
    res.status(200).send(JSON.stringify({
      "status": 200,
      "statusText": "succcess"
    }));
  });

My Node.js Endpoint:

app.post('/test', function (req,res) {
  console.log(req.body.test);
  res.setHeader('Content-Type', 'application/json');

  res.status(200).send(JSON.stringify({
    "status":200,
    "statusText":"succcess"
  }));
});

AJAX Error Message:

{"readyState":0,"status":0,"statusText":"error"}

Phil
  • 157,677
  • 23
  • 242
  • 245
user964627
  • 655
  • 3
  • 14
  • 24
  • Is the server giving any output, is console.log(req.body.test); actually firing? – Lukas Bach Mar 28 '18 at 23:31
  • 1
    You say "talking to the endpoint is a success". How do you know that? The status of 0 suggests you never reached the server. – see sharper Mar 28 '18 at 23:32
  • I can see the console log for req.body.test. – user964627 Mar 28 '18 at 23:34
  • 2
    status 0 usually happens when you have a CORS error - check the **browser** console - the console you're talking about is the server console, which isn't where the problem is - I'm guessing that `http://localhost:1234/` isn't the same server that web page is load by. – Jaromanda X Mar 28 '18 at 23:34
  • I added, res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888'); to my route response and it seems to be working now. The success function is being called now. – user964627 Mar 28 '18 at 23:42

0 Answers0