-1

I am having an odd issue making a POST request to my express app.

I have tested the API using Postman however when I copy the request code from Postman either the AJAX or XHR the request fails and the express app returns an undefined express body.

The console on the site spits out the following:

Resource interpreted as Document but transferred with MIME type application/json

The request looks like this (AJAX):

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://thedomainhere.com/hello",
  "method": "POST",
  "headers": {
    "content-type": "application/json",
    "cache-control": "no-cache",
    "postman-token": "0158785a-7ff5-f6a3-54ba-8dfc152976fc"
  },
  "data": {
    "senderEmail": "hello@hello.com"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

Why would this work on Postman and in the console using Curl, but not from a web document?

Vadim
  • 8,701
  • 4
  • 43
  • 50
dylankbuckley
  • 1,507
  • 1
  • 13
  • 21

2 Answers2

0

jQuery first makes OPTIONS request without POST payload, when you try to make cross-origin ajax, and expects the following headers to be sent in response:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept

To set headers on response in Express you can do the following middleware somewhere in the beginning (also see NodeJS docs for setHeader):

app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'POST');
    res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    if(req.method == 'OPTIONS') {
        res.end();
    } else {
        next();
    }
});

Also this post about enabling CORS on express may be useful.

To understand why OPTIONS is sent in this case, you can read an answer to this question.

That's the first possible reason, why you get empty body.

Also try to change content-type to contentType (as in jQuery docs) and pass a string in the data

data: JSON.stringify({
    "senderEmail": "hello@hello.com"
})
Community
  • 1
  • 1
Vadim
  • 8,701
  • 4
  • 43
  • 50
0

You should set the response type to text/html like this, for example:

app.post("/route", function(req, res) {
    ...
    res.set('Content-Type', 'text/html'); // or 'text/plain', etc.
    ...
    res.send();
});
gjegadesh
  • 144
  • 10