node.jshttp-headersbody-parserget-headers

How to get read headers in node.js using body-parser?


I am tring to create a demo API server using node.js, express4 and body-parser. I am trying to secure it using some Api-Key which will have to be passed in the request header. However, I am not able to do it.

I tried

console.log(bodyParser.getheader("Api-Key"))

and

console.log(app.getheader("Api-Key"))

but in both cases I get the error

getheader is not a function

So now can I read headers using body parser?


Solution

  • There is no .getHeader(). To get the headers of a request, use req.get() (or its alias req.header()). For example:

    var app = express()
    
    app.use(function (req, res, next) {
      console.log(req.get('Api-Key'))
      next()
    })
    

    See the Express 4 docs for req for more information.