简体   繁体   中英

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

尝试

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM