简体   繁体   English

如何在Node.js中创建派生的http(s)服务器?

[英]How do I create a derived http(s) server in Node.js?

I want to derive the Node.js http(s) server, as I need to add some behavior. 我想派生Node.js http(s)服务器,因为我需要添加一些行为。

Eg, I want to have an http server that also has a foobar function. 例如,我想要一个也具有foobar功能的http服务器。 So I want to be able to do something like this: 所以我希望能够做到这样的事情:

var server = http.createServer(function (req, res) { ... }).listen(3000);
server.foobar();

Of course I somehow need to derive from the http module, but how could I do this? 当然我不知何故需要从http模块派生,但我怎么能这样做呢? Apparently there is no Http constructor I could override ... 显然没有我可以覆盖的Http构造函数...

Any ideas or hints? 任何想法或提示?

I haven't tested, but giving in it a though I would say you would only have to: 我没有测试过,但是虽然我会说你只需要:

var http = require('http');
http.Server.prototype.foobar = function () {};

As you can see here the createServer function is nothing but a factory instantiating a new Server object that was exposed two lines before. 正如您在此处所看到的,createServer函数只是一个工厂,实例化之前暴露过两行的新Server对象。

The correct way is to create a subclass of the server. 正确的方法是创建服务器的子类。

var http = require('http')

class MyServer extends http.Server {
  foobar () {
    // any code
  }
}

var server = new MyServer(function (req, res) {
  // any code
})

If you are running a version of Node.js that is <1.0 you need to use the old class syntax: 如果您运行的Node.js版本<1.0,则需要使用旧的类语法:

var http = require('http')

function MyServer (handler) {
  http.Server.call(this, handler)
}

MyServer.prototype = Object.create(http.Server.prototype)

MyServer.prototype.foobar = function () {
  // any code
}

var server = new MyServer(function (req, res) {
  // any code
})

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

相关问题 如何在运行Apache的DreamHost VPS上使用Node.js创建HTTP服务器? - How do I create an HTTP server with Node.js on a DreamHost VPS running Apache? 如何立即关闭 Node.js http(s) 服务器? - How do I shutdown a Node.js http(s) server immediately? Node.JS:如何创建HTTP聊天服务器? - Node.JS: How to create a HTTP Chat Server? 如何在node.js中打印HTTP服务器的地址? - How do you print the address of an http server in node.js? 如何将带有Node.js的HTTP请求发送到由LocalTunnel托管的Node.js服务器 - How to send http(s) requests with Node.js to a Node.js server hosted with LocalTunnel 如何找出 Node.js 中的 HTTP 服务器有多少连接的客户端? - How do I find out how many connected clients there are to a HTTP Server in Node.js? 如何执行对由node.js服务器处理的http请求的查询字符串中的特定参数序列的检查? - How do I enforce a check for a particular sequence of parameters in the querystring of an http request handled by a node.js server? 如何以编程方式停止 Node.js HTTP 服务器以便进程退出? - How do I stop a Node.js HTTP server programmatically such that the process exits? 使用 HTTP2 模块时如何在 Node.js 中获取客户端的 IP 地址? - How do I get the client's IP address in Node.js when using the HTTP2 module? 如何将自定义HTTP标头发送到Node.js - How do I send custom HTTP header to Node.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM