📜  Node.js Http2ServerRequest.headers 方法(1)

📅  最后修改于: 2023-12-03 14:44:39.354000             🧑  作者: Mango

Node.js Http2ServerRequest.headers 方法
介绍

在 Node.js 中,Http2ServerRequest 对象代表了 HTTP2 协议中的客户端请求。Http2ServerRequest 对象提供了一个 headers 方法,用于获取客户端请求的头部信息。

语法
request.headers;
返回值

返回一个对象,该对象包含了客户端请求的头部信息。每个头部字段名都是对象的属性名,对应的属性值是一个字符串数组,因为某些头部字段可以出现多次。

示例
const http2 = require('http2');

const server = http2.createServer();

server.on('stream', (stream, headers) => {
  const request = stream.request;
  
  // 获取客户端请求的头部信息
  const requestHeaders = request.headers;
  
  console.log(requestHeaders);
});

server.listen(8080);

输出结果:

{
  ':method': ['GET'],
  ':scheme': ['https'],
  ':path': ['/'],
  ':authority': ['localhost:8080'],
  'user-agent': ['Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'],
  'accept-encoding': ['gzip, deflate, br'],
  'accept-language': ['en-US,en;q=0.9'],
  'x-custom-header': ['custom value']
}
备注
  • Http2ServerRequest.headers 方法仅适用于 HTTP2 协议的客户端请求。
  • 头部字段名不区分大小写,但是推荐使用小写字母的参数名。
  • Http2ServerRequest.headers 方法返回的对象是只读的,任何修改都不会对请求产生任何影响。
  • 在 HTTP2 协议中,':method'、':scheme'、':path' 和 ':authority' 是预定义的伪头部字段,存储在 headers 对象中。其他的头部字段均以普通字段的方式存储在 headers 对象中。
参考链接