How to avoid preflight OPTIONS request with node request package for CORS?

3.5k views Asked by At

I simply wish to post some json but by default request does a preflight OPTIONS request.

I would like to avoid this as users often have unreliable connections, an extra request further reduces reliability and results in cryptic error messages like 'CORS rejected'.

var request = require('request');
function (data, cb) {
  if (!cb) cb = function () {};
  request({
    method: "POST",
    url: "someurl",
    json:true,
    body: data
  }, function (err, response, body) {
    if (err) cb(err);
    else if (response.statusCode != 200) {
      cb(new Error("log satus code: " + response.statusCode));
    } else {
      cb(null, body);
    }
  })

To clarify I am doing an actual CORS and wish to avoid the preflight OPTIONS request. I also have control over the serve (though that shouldn't matter).

2

There are 2 answers

0
Jason Desrosiers On BEST ANSWER

The prefight OPTIONS request is a required part of the CORS flow. There is no way around it. However, the client can cache the preflight response so it only needs to actually make the preflight request once instead of every time it POSTs.

To enable preflight request caching, the preflight request must respond with the Access-Control-Max-Age header. The value of this header is the number of seconds the client is allowed to cache the response.

For example, the following response header will allow the client to cache the preflight response for 5 minutes.

Access-Control-Max-Age: 300

You will have to choose a value that is appropriate for your application. It is usually a good idea to set this value to something that isn't too large in case you need to change the preflight response in the future. If you allow the preflight request to be cached for a month, users might not get your changes until their cache expires a month later.

0
devin_s On

Simple requests don't need a preflight request. I'm guessing the json: true sets a custom Content-Type header (most likely application/json).

The simple values for Content-Type are:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

Anything outside of those values will trigger a preflight request.