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

江枫思渺然 提交于 2021-01-26 09:15:34

问题


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

回答1:


try

console.log("res._headers >>>>>>>" + JSON.stringify(res._headers));



回答2:


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


来源:https://stackoverflow.com/questions/32732507/how-to-get-list-of-http-response-headers-currently-set-in-node-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!