req.headers contain in Express?In an Express app, what kind of data does req.headers hold?
app.get('/', (req, res) => {
res.json(req.headers);
});Think about how HTTP headers are structured and how Express exposes them.
req.headers is a plain JavaScript object where each key is a header name in lowercase, and the value is the header's value as a string.
req.headersWhich code correctly gets the value of the content-type header from req.headers in Express?
app.post('/data', (req, res) => { const contentType = /* fill here */; res.send(contentType); });
Header names in req.headers are all lowercase.
Express stores header names in lowercase in req.headers, so you must use lowercase keys to access them.
req.headers['Authorization'] return undefined?Given this code snippet, why might req.headers['Authorization'] be undefined?
app.get('/secret', (req, res) => {
const auth = req.headers['Authorization'];
res.send(auth || 'No auth');
});Check how Express normalizes header names in req.headers.
Express converts all header names to lowercase in req.headers. Accessing with uppercase letters returns undefined.
req.headers?Consider this Express route:
app.get('/test', (req, res) => {
console.log(req.headers);
res.send('ok');
});If a client sends a request with headers:
{
'Host': 'example.com',
'User-Agent': 'curl/7.68.0',
'Accept': '*/*'
}What will be logged to the console?
Remember how Express formats header names in req.headers.
Express lowercases all header names in req.headers and stores them as keys in an object.
req.headers directly in Express?In Express, what is the main reason you should not change req.headers directly inside a middleware or route handler?
Think about how middleware and routing depend on request data.
Changing req.headers can confuse later middleware or route handlers that expect the original headers, leading to bugs or security issues.