📜  Node.js http.ClientRequest.getHeader() API

📅  最后修改于: 2022-05-13 01:56:40.813000             🧑  作者: Mango

Node.js http.ClientRequest.getHeader() API

http.ClientRequest.getHeader()是 http 模块中 ClientRequest 类的内置应用程序编程接口,用于获取特定标头名称的标头对象。

句法:

const request.getHeader(name)

参数:此方法将标头的名称作为参数。

返回值:此方法将标头的对象作为输出返回。

示例 1:

Javascript
// Node.js program to demonstrate the 
// request.getHeader() APi
 
// Importing http module
const http = require('http');
 
// Create an HTTP server
http.createServer((req, res) => {}).listen(3000, '127.0.0.1', () => {
 
  // getting client request
  const req = http.request({
    port: 3000,
    host: '127.0.0.1',
  });
 
  req.setHeader('content-type', 'text/html');
 
  // getting header
  // by using getHeader() api
  console.log("header :- " + req.getHeader('content-type'))
 
  process.exit(0)
});


Javascript
// Node.js program to demonstrate the 
// request.getHeader() APi
 
// Importing http module
const http = require('http');
 
// Create an HTTP server
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('okay');
});
 
// Now that server is running
server.listen(3000, '127.0.0.1', () => {
 
  // make a request
  const options = {
    port: 3000,
    host: '127.0.0.1',
    headers: {
      'Connection': 'Upgrade',
      'Upgrade': 'websocket'
    }
  };
 
  // getting client request
  const req = http.request(options);
 
  req.setHeader('Cookie', ['type=ninja', 'language=javascript']);
 
  // getting header
  // by using getHeader() api
  const v = req.getHeader('Cookie');
 
  // display the result
  console.log("header :- " + v)
 
  process.exit(0)
});


输出:

示例 2:

Javascript

// Node.js program to demonstrate the 
// request.getHeader() APi
 
// Importing http module
const http = require('http');
 
// Create an HTTP server
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('okay');
});
 
// Now that server is running
server.listen(3000, '127.0.0.1', () => {
 
  // make a request
  const options = {
    port: 3000,
    host: '127.0.0.1',
    headers: {
      'Connection': 'Upgrade',
      'Upgrade': 'websocket'
    }
  };
 
  // getting client request
  const req = http.request(options);
 
  req.setHeader('Cookie', ['type=ninja', 'language=javascript']);
 
  // getting header
  // by using getHeader() api
  const v = req.getHeader('Cookie');
 
  // display the result
  console.log("header :- " + v)
 
  process.exit(0)
});

输出:

参考:https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_request_getheader_name