0

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?

Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92

1 Answers1

2

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.

Trott
  • 66,479
  • 23
  • 173
  • 212
  • But I will have to do that in all requests, I want to do it oin a common place, and if this fails, not move forward – Ayush Gupta Apr 05 '17 at 04:18
  • If you want a middleware to execute for every request, don't provide a route. (I've updated the answer to show this.) – Trott Apr 05 '17 at 04:22