我对服务器开发和 NodeJS 完全陌生,所以如果这个问题听起来很愚蠢或者这样的问题已经存在,我深表歉意。
我正在学习一个简单的 NodeJS 教程并构建一个简单的“Hello World”服务器。我注意到http.createServer只有一个函数作为它的参数。
http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type' : 'text/html'});
res.end("Hello World");
}.listen(8080);
Run Code Online (Sandbox Code Playgroud)
我尝试将另一个函数传递给它,如下所示:
var http = require('http');
http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type':'text/html'});
res.end("Hello World");
},
function (req, res) {
res.write("Blahblah");
res.end();
}
).listen(8080);
Run Code Online (Sandbox Code Playgroud)
但是命中localhost:8080只返回Hello World。
所以我想知道我是否可以将多个函数传递给它,如果不能,那为什么。
感谢您的时间
您不能传递多个函数。如果您想要多个传入请求的侦听器,则可以为传入请求注册另一个侦听器:
const server = http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type' : 'text/html'});
res.end("Hello World");
}.listen(8080);
// add additional listener
server.on('request', function(req, res) {
if (req.url === "/goodbye") {
res.writeHead(200, {'Content-Type' : 'text/plain'});
res.end("goodbye");
}
});
Run Code Online (Sandbox Code Playgroud)
注意:从doc for 开始http.createServer(),它说明了传递给 的函数参数http.createServer():
http.createServer([options][, requestListener])
requestListener 是一个自动添加到“请求”事件的函数。
请求事件的文档在这里。
正如其他人所说,很少使用像这样的普通 http 服务器,因为一些简单的路由几乎总是有用的,像Express这样的轻量级框架提供了非常有用的功能,而不会真正妨碍您做任何事情。在 Express 的情况下,您将使用如下代码:
const express = require('express');
const app = express();
// define handler for /goodbye URL
app.get('/goodbye', function(req, res) {
res.send("goodbye");
});
// define handler for /hello URL
app.get("/hello", function(req, res) {
res.send("hello");
});
const server = app.listen(8080);
Run Code Online (Sandbox Code Playgroud)
在这里 express,保留您希望处理的 URL 列表,然后侦听每个传入请求,将其与您想要处理的 URL 进行比较并调用适当的路由处理程序。它还有许多其他路由功能,例如中间件、通配符、参数化 URL 等...
| 归档时间: |
|
| 查看次数: |
1800 次 |
| 最近记录: |