Home > Back-end >  request not showing all headers nodejs
request not showing all headers nodejs

Time:01-04

I am using nodejs with express. I have a middleware to check the authorization token sent through the headers in the request.

Previously, I was setting the middleware in each endpoint, one by one. Everything worked perfectly, the headers were correctly sent in the request. I'm doing it with authorization bearer, so in my auth middleware, I check if there's an "Authorization" header.

Now I moved the middleware to the server.js, to wrap all the routes, so I don't have to set it manually. There are some routes that are unprotected so I am excluding them from the middleware with the "unless" function.

const unless = function(path, middleware) {
    return function(req, res, next) {
        let reqMethod = req.method;
        if(req.method == 'OPTIONS'){
            reqMethod = req.headers['access-control-request-method'];
        }
        if (path.find(({url,method,methods}) => url == req.path && (method==reqMethod || methods==reqMethod))) {
            next();
        } else {
            middleware(req, res, next);
        }
    };
};

app.use(schemaValidator,unless(publicPaths,auth),routes);

The "unless" method seems to work fine with the unprotected routes. The problem now is that, for some reason, I'm not getting the request headers as I used to. Instead of getting the "Authorization" header with the token, I'm just getting this:

"access-control-request-headers":"authorization".

And if I check for the req.headers.authorization it is undefined.

Side note: the publicPaths is an array of objects with the "URL" and "method" of the unprotected endpoints as the keys.

Does anyone know what might be happening? If you need any more information please tell me!

CodePudding user response:

Handling preflight OPTIONS requests is an entirely separate concern to authorisation.

Preflight requests typically will not have any Authorisation header present. I highly recommend using the industry standard cors middleware, registered before any other request handling middleware

const cors = require("cors");
const corsOptions = {
  origin: ["https://example.com"],
};

const unless = function (path, middleware) {
  return function (req, res, next) {
    if (
      paths.some(
        ({ url, method, methods }) =>
          url === req.path && (method === req.method || methods === req.method)
      )
    ) {
      next();
    } else {
      middleware(req, res, next);
    }
  };
};

app.use(schemaValidator, cors(corsOptions), unless(publicPaths, auth), routes);

This will take care of OPTIONS requests independently, leaving your middleware to work with actual requests.


You won't see any issues with Postman since it is not subject to the same-origin policy and will not send preflight OPTIONS requests.

  • Related