函数传递是如何让HTTP服务器工作的

带着这些知识,我们再来看看我们简约而不简单的HTTP服务器:

var http = require("http"); //加载http模块

http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}).listen(8888);

现在它看上去应该清晰了很多:我们向 createServer 函数传递了一个匿名函数。

用这样的代码也可以达到同样的目的:

var http = require("http");

function onRequest(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}

http.createServer(onRequest).listen(8888);

最清晰的思路是
// 加载http模块
var http = require('http');
// 创建http服务
var server = http.createServer();
// 服务器对象监听客户端request事件
server.on('request',function (req,res) {
// req 代表请求对象 request
// res 代表响应对象 response
console.log('连接成功');
res.setHeader("Content-type","text/html;charset=utf-8"); //响应为html文本
res.end('哈哈哈,我捡到五毛钱。。。');//结束响应
});
// 启动http服务,监听端口
server.listen('3000','10.36.135.97',function () {
console.log('服务器启动成功');
});
 
原文地址:https://www.cnblogs.com/shenlan88/p/11061887.html