📜  Node.js http.ClientRequest.abort() 方法

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

Node.js http.ClientRequest.abort() 方法

http.ClientRequest.abort()是 http 模块中客户端请求类的内置应用程序编程接口,用于中止客户端请求。

句法:

ClientRequest.abort()

参数:此方法不接受任何参数作为参数。

返回值:此方法不返回任何值

示例 1:文件名:index.js

Javascript
// Node.js program to demonstrate the 
// request.abort() 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', () => {
    console.log("Server is started")
 
    // Making a request
    const options = {
    port: 3000,
    host: '127.0.0.1',
    headers: {
      'Connection': 'Upgrade',
      'Upgrade': 'websocket'
    }
  };
 
  // Getting client request
  const req = http.request(options);
 
  // Aborting the request
  // by using abort() method
  req.abort()
 
  // Emit the message
  req.on('abort',()=>{
    console.log("client request is aborted")
     
  })
});


Javascript
// Node.js program to demonstrate the 
// request.abort() APi
 
// Importing http module
const http = require('http');
 
// Creating 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',
  });
 
  // Aborting the request
  // by using abort() api
  req.abort()
 
  // Emit the message
  req.on('abort',()=>{
    console.log("client request is aborted")
    process.exit(0);
  })
});


使用以下命令运行index.js 文件

node index.js

输出:

client request is aborted

示例 2:文件名:index.js

Javascript

// Node.js program to demonstrate the 
// request.abort() APi
 
// Importing http module
const http = require('http');
 
// Creating 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',
  });
 
  // Aborting the request
  // by using abort() api
  req.abort()
 
  // Emit the message
  req.on('abort',()=>{
    console.log("client request is aborted")
    process.exit(0);
  })
});

使用以下命令运行index.js 文件

node index.js

输出:

client request is aborted

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