JQuery.ajax sending both parameters and POST, how to handle Express.js (Node.js)

Whenever my app sends an ajax request to the server:

$.ajax({
    url: config.api.url + '/1/register', 
    type: 'POST', 
    contentType: 'application/json',
    data: /* some JSON data here */,

    /* Success and error functions here*/
});

      

It sends the following two requests:

Request URL:https://api.example.com/1/register
Request Method:OPTIONS
Status Code:404 Not Found

      

Then the corresponding ones follow POST

with all the data. Since I am handling routes as such:

expressApp.post('/1/register', UserController.register);

      

And there is no route for this .options

, it always ends with 404

. This is the same for almost all methods. This question talks a bit about this in the two answers below the accepted one, but I'm not really sure what to do about it.

How can I handle this? Should I add a route .options

, and if so, what should it do?

0


source to share


1 answer


I only really did it today. Here's the gist that solved my problem.




Node.js. You must first respond to the OPTIONS request. Something like that.

if (req.method === 'OPTIONS') {
      console.log('!OPTIONS');
      var headers = {};
      // IE8 does not allow domains to be specified, just the *
      // headers["Access-Control-Allow-Origin"] = req.headers.origin;
      headers["Access-Control-Allow-Origin"] = "*";
      headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
      headers["Access-Control-Allow-Credentials"] = false;
      headers["Access-Control-Max-Age"] = '86400'; // 24 hours
      headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
      res.writeHead(200, headers);
      res.end();
} else {
//...other requests
}

      




Place this anywhere you have a query with this problem. I set it to a function variable checkIfOption

and call it like this:

app.all('/', function(req, res, next) {
  checkIfOption(req, res, next);
});

      

And instead, //...other requests

I callednext();

This worked well for me.

+5


source







All Articles