简体   繁体   中英

jQuery.ajax sending both OPTIONS and POST, how to handle with Express.js (Node.js)

Whenever my application 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

Followed by the appropriate POST with all of the data. Since I handle the routes as such:

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

And do not have a .options for this route, it always ends up in 404 . It's the same for nearly all methods. This question talks a little bit about it in the two answers below the accepted one, but I'm not quite sure what to make of it.

How can I handle this? Should I be adding .options route and if so what should it do?

I actually dealt with this just today. Here's the gist which solved my problem.


Node.js cross-origin POST. You should response for OPTIONS request first. Something like this.

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
}

Put this in anywhere that you have a request with this problem. I set it to a checkIfOption function variable and call it like so:

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

And in the place of //...other requests I called next();

This worked well for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM