📜  req.header express.js - Javascript (1)

📅  最后修改于: 2023-12-03 15:04:53.348000             🧑  作者: Mango

req.header in Express.js

In Express.js, req.header is a method that returns the value of the specified header field in the HTTP request sent to the server by the client.

Syntax
req.header(name);

Where:

  • name: the name of the header field to retrieve the value of.
Return Value(s)
  • If name is the name of a single header field, req.header(name) returns its value as a string.
  • If name is the name of a set of header fields (e.g. Accept), req.header(name) returns an array with the values of all the fields in the set.
Usage

To use req.header, you must first install and import Express.js:

const express = require('express');
const app = express();

Then, in your application's logic, you can use req.header to retrieve the value of a header field from the request object:

app.get('/', (req, res) => {
  const headerValue = req.header('User-Agent');
  console.log(headerValue);
  // Output: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299
});

You can also retrieve the values of multiple headers with a single call to req.header, passing in the name of the header set:

app.get('/', (req, res) => {
  const acceptHeaders = req.header('Accept');
  console.log(acceptHeaders);
  // Output: [ 'text/html', 'application/xhtml+xml', 'application/xml;q=0.9', 'image/webp', '*/*;q=0.8' ]
});
Conclusion

req.header is a useful method in Express.js that allows you to quickly and easily retrieve the values of header fields in HTTP requests sent to your server. With its simple syntax and flexible return values, this method makes working with HTTP headers a breeze in your application's logic.