Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list of HTTP response headers currently set in Node/Express?

As I understand, when you are building a http response in node/express or whatever, the process consists of primarily two non-sequential steps: defining Headers and constructing the body. Headers include Set-Cookie headers. In Express, the following methods are available with the response object for setting headers:

res.append(); // To append/create headers
res.cookie(); // A convenience method to append set-cookie headers.

As headers are only buffered and not actually sent until the response is sent, is there any method or mechanism to get the current list of headers set, along with their values, something like:

 headers = res.getHeaders(); //Returns an object with headers and values
 headers = res.getHeaders('Set-Cookie'); // To get only select headers
like image 372
Sunny Avatar asked Sep 23 '15 06:09

Sunny


2 Answers

try

console.log("res._headers >>>>>>>" + JSON.stringify(res._headers));
like image 76
Sourbh Gupta Avatar answered Sep 30 '22 19:09

Sourbh Gupta


I've managed to inspect what is being sent (including cookies) using response.getHeaders() (available since Node 7.7.0) in combination with on-headers's module. Something like this:

import express from 'express'
import onHeaders from 'on-headers'

const router = express.Router()

function responseDebugger() {
  console.log(JSON.stringify(this.getHeaders()))
}

router.post('/', (req, res, next) => {
  onHeaders(res, responseDebugger)

  res.json({})
})

export default router
like image 45
Pedro Andrade Avatar answered Sep 30 '22 20:09

Pedro Andrade