基础HTTP服务器
const http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
浏览器访问 http://localhost:8888/ 会看到一个写着“Hello World”的网页
HTTP服务器分析
const http = require("http");
第一行请求Node.js
自带的http
模块,并且把它赋值给 http 变量
http.createServer(function(request, response) {
}).listen(8888);
然后调用http模块提供的方法:createServer,这个方法会返回一个对象,这个对象有一个listen
方法,这个方法输入一个数值参数,指定http服务器的端口号
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
然后向*createServer*
函数传递了一个匿名函数,服务器收到一个请求,这个函数就会被调用。
当这个匿名函数被出发时,有两个参数传入:request
和response
request
:用来处理请求
response
:用来处理响应
当收到请求时response.writeHead
发送一个状态码和http的响应头的类型,response.write
发送写入的文本到页面,最后调用response.end()
来完成响应