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

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

Node.js http.ClientRequest.end() API

http.ClientRequest.end()是http 模块中ClientRequest 类的内置应用程序编程接口,用于完成请求的发送。如果身体的任何部位未发送。

句法:

const request.end([data[, encoding]][, callback])

参数:此方法将数据作为输入。

返回值:此方法只返回一个回调函数。

示例 1:

Javascript
// Node.js program to demonstrate the 
// request.end() 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');
 
  // finishing sending the request
  req.end()
 
  // getting header
  // by using getHeader() api
  console.log("header :- " + req.getHeader('content-type'))
 
  process.exit(0)
});


Javascript
// Node.js program to demonstrate the 
// request.end() 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');
 
 
  // finishing sending the request
  req.end()
 
 
  // display the result
  console.log("header :- " + v)
 
  process.exit(0)
});


输出:

示例 2:

Javascript

// Node.js program to demonstrate the 
// request.end() 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');
 
 
  // finishing sending the request
  req.end()
 
 
  // display the result
  console.log("header :- " + v)
 
  process.exit(0)
});

输出:

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