
This assumes you are already familiar with Express. If not, check out my article FreeKB - Node.js - Getting Started with Client Server Express on Docker.
req.headers can be used to return request headers. Let's say you have the following Express app.
import express from "express"
const app = express()
const timestamp = () => Date()
app.get('/', (req, res) => {
console.log(`${timestamp()} Hello Console`)
console.log(req.headers)
res.send(`${timestamp()} Hello World`)
})
app.listen(12345)
console.log(`Node.js app is up and running!`);
Running this app should return something like this in the console log.
{
host: 'ec2-10-11-12-13.compute-1.amazonaws.com:12345',
connection: 'keep-alive',
'cache-control': 'max-age=0',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'accept-encoding': 'gzip, deflate',
'accept-language': 'en-US,en;q=0.9',
'if-none-match': 'W/"4a-/FSUEfQFHje+zHfoaKfyjp/nKEE"'
}
And here is now you can return a specific request header, "host" in this example.
import express from "express"
const app = express()
const timestamp = () => Date()
app.get('/', (req, res) => {
console.log(`${timestamp()} Hello Console`)
console.log(req.headers.host)
res.send(`${timestamp()} Hello World`)
})
app.listen(12345)
console.log(`Node.js app is up and running!`);
And you probably should have an if / else statement to determine if the header is defined.
import express from "express"
const app = express()
const timestamp = () => Date()
app.get('/', (req, res) => {
console.log(`${timestamp()} Hello Console`)
if (req.headers.host == undefined) {
console.log("req.headers.host is undefined")
} else {
console.log(req.headers.host)
}
res.send(`${timestamp()} Hello World`)
})
app.listen(12345)
console.log(`Node.js app is up and running!`);
req.query can be used to get Request Parameters. For example, let's say a request is submitted to ec2-10-11-12-13.compute-1.amazonaws.com:12345/?foo=bar. Check out my article FreeKB - Node.js - GET URL Parameters.
import express from "express"
const app = express()
const timestamp = () => Date()
app.get('/', (req, res) => {
console.log(`${timestamp()} Hello Console`)
if (req.headers.host == undefined) {
console.log("req.query.foo is undefined")
} else {
console.log(req.query.foo)
}
res.send(`${timestamp()} Hello World`)
})
app.listen(12345)
console.log(`Node.js app is up and running!`);
Did you find this article helpful?
If so, consider buying me a coffee over at