简体   繁体   English

http.createServer方法中添加了选项参数的用例是什么

[英]What Is The Use Case Of Options Argument Added to http.createServer Method

Upon going through the node.js documentation I realized the createServer method on the http module has been updated to receive an options argument. 通过查看node.js文档后,我意识到http模块上的createServer方法已更新为接收options参数。 It was not included before in previous versions of node.js if I remember correctly 如果我没记错的话,它在以前版本的node.js中没有包括在内

http.createServer([options][, requestlistener])

Link: https://nodejs.org/dist/latest-v10.x/docs/api/http.html#http_http_createserver_options_requestlistener 链接: https//nodejs.org/dist/latest-v10.x/docs/api/http.html#http_http_createserver_options_requestlistener

It is not clear what the options can be used for but it is an object that has the properties IncomingMessage and ServerResponse . 目前尚不清楚这些选项可以用于什么,但是它是一个具有IncomingMessageServerResponse属性的对象。

I just want clarification on what it can be used for and a code example. 我只想澄清它的用途以及代码示例。

The server does create an IncomingRequest and ServerResponse instance for each request it receives, and passes them to the request event listener - they are the objects that you receive in the typical (req, res) => { … } functions. 服务器确实会为它接收到的每个请求创建一个IncomingRequestServerResponse实例,并将它们传递给request事件侦听器-它们是您在典型的(req, res) => { … }函数中接收的对象。

In particular they are instantiated here and there , in the internals of the http library (and also, similarly, in the https and http2 libraries). 特别是,它们在http库的内部(以及类似地,在https和http2库中)在这里那里实例化。 The createServer options allow you to customise which classes exactly are used for these objects. createServer选项使您可以自定义哪些类别完全用于这些对象。 A simple example: 一个简单的例子:

import { IncomingMessage, ServerResponse, createServer } from 'http';

class MyIncomingMessage extends IncomingMessage {
  …
}
class MyServerResponse extends ServerResponse {
  …
}

const server = createServer({
  IncomingMessage: MyIncomingMessage,
  ServerResponse: MyServerResponse,
});
server.on('request', (req, res) => {
  console.assert(req instanceof MyIncomingMessage);
  console.assert(res instanceof MyServerResponse);

  res.statusCode = 200;
  res.end('Hello!');
});

A simple customisation would be adding your own methods, and otherwise inheriting from the builtin default classes. 一个简单的自定义方法是添加您自己的方法,否则从内置的默认类继承。 You could also overwrite some methods, or you could roll your own implementation. 您也可以覆盖某些方法,也可以滚动自己的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM