Sunday 26 April 2020

Why request.getHeader doesn't work on request object on NodeJS server handler?

Hello. I've been playing with NodeJS and reading, and probably I'm missing something. As I learned, it is possible to use ClientRequest object to invoke REST APIs from NodeJS itself in a vanilla way (more complicated that just use Axios, but still).As I could check, I can set and get headers from it using setHeader() and getHeader() in the following way:const req = http.request({});req.setHeader('Content-Type', 'application/json');req.getHeader('Content-Type');but, when using ClientRequest for handling incoming requests in a NodeJS server, using getHeader() does not work, returning the error function req.getHeader() function does not exist. As I learned later, you can do request.headers to access an array of headers with lowercase names to not to worry about casing.const server = http.createServer((req, res) => {//const contentType = req.getHeader('content-type'); --Doesn't workconst contentType = req.headers['content-type]; // It works!...}However I don't get why getHeader() only works in a context but not in the other.

Submitted April 26, 2020 at 06:52PM by anicetito

No comments:

Post a Comment