我有一个现有的模块,它创建了一个普通的http服务器。它可以启动服务器并在端口上侦听,也可以在不启动的情况下公开服务器
我想延长一些航线,但不使用两个港口,用特快专递
有可能吗?
const http = require('http')
const express = require('express')
const app = express()
app.get('/bar', (req, res) => {
res.json({msg: 'fox'})
})
const server = http.createServer((req, res) => {
if (req.url === '/foo') {
res.writeHead(200, {'Content-Type': 'text/html'})
res.end()
}
})
// TODO: how to merge app and server?
const merged = howToMerge(server, app)
merged.listen(5000)
要将Express挂接到已经创建的纯http服务器,只需要为request
事件注册app
变量,如下所示:
server.on('request', app);
这正是向http.createServer()
传递回调的作用。
这里有一个单独创建http服务器的工作应用程序:
const http = require('http');
const app = require('express')();
const server = http.createServer((req, res) => {
if (req.url === '/foo') {
console.log("plain handler", req.url);
res.writeHead(200, {'Content-Type': 'text/plain'})
res.end("foo");
}
});
app.get("/demo", (req, res) => {
console.log("expess handler", req.url);
res.send("demo");
});
app.use((err, req, res, next) => {
// only handle error if someone hasn't already sent a response
if (!res.headersSent) {
res.status(404).send("Error 404");
}
});
// register Express app as a handler for the request event
server.on('request', app);
server.listen(80);
注意:当使用像这样的两个独立系统时,由于request
事件的两个事件处理程序(传递给createServer()
的一个和注册到server.on('request', ...)
的一个将在每个http请求上被调用,即使其中一个已经处理了它。这是因为这两个系统并不是为了以这种方式协同工作而构建的。实际上,您有两个独立的事件侦听器试图处理每个请求。您可能偶尔需要检查res.headersSent
,看看另一个是否已经处理了请求。
如果你想了解node.js的工作原理,你可以看到http.createServer()
只是这个代码:
function createServer(opts, requestListener) {
return new Server(opts, requestListener);
}
并且,Server对象是Net.Server的子类,构造函数包含以下代码:
if (requestListener) {
this.on('request', requestListener);
}
类似的东西
const http = require('http')
const express = require('express')
const app = express()
app.use(function (req, res, next) {
if (req.url === '/foo') {
res.writeHead(200, { 'Content-Type': 'text/html' })
res.end()
} else {
next()
}
})
app.get('/bar', (req, res) => {
res.json({ msg: 'fox' })
})
const server = http.createServer(app)
server.listen(5000)