Skip to content

Instantly share code, notes, and snippets.

@abskmj
Last active September 21, 2020 05:55
Show Gist options
  • Save abskmj/cef6d790d1b8778ce37eafc178b550ce to your computer and use it in GitHub Desktop.
Save abskmj/cef6d790d1b8778ce37eafc178b550ce to your computer and use it in GitHub Desktop.
Express middleware to log request and response headers
const express = require('express')
const app = express()
const port = 3000
/**
* Express middleware to log request and response headers
*/
app.use((req, res, nxt) => {
const requestHeaders = req.headers
console.log('Request Headers:', requestHeaders)
// Request Headers: {
// 'user-agent': 'PostmanRuntime/7.24.1',
// accept: '*/*',
// 'cache-control': 'no-cache',
// 'postman-token': '74416f71-0d09-453f-b714-3737dfd9f6b4',
// host: 'localhost:3000',
// 'accept-encoding': 'gzip, deflate, br',
// connection: 'keep-alive'
// }
res.on('finish', () => {
const responseHeaders = res.getHeaders()
console.log('Response Headers:', responseHeaders)
// Response Headers: [Object: null prototype] {
// 'x-powered-by': 'Express',
// 'content-type': 'text/html; charset=utf-8',
// 'content-length': '12',
// etag: 'W/"c-Lve95gjOVATpfV8EL5X4nxwjKHE"'
// }
})
nxt()
})
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Listening at http://localhost:${port}`))
{
"name": "express-req-res-headers",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node ."
},
"keywords": [],
"author": "abskmj@gmail.com",
"license": "MIT",
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"standard": "^14.3.3"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment