Node.js-http模块
服务器相关的概念
IP地址:IP地址是互联网上的一个唯一标识,一台电脑的IP地址可以在互联网上被其他电脑访问到。
互联网中每台web服务器,都有自己的IP地址
域名和域名服务器:
端口号:
创建web服务器的基本步骤:
1.导入http模块
2.创建web服务器实例
3.为服务器实例绑定request事件,监听客户端的请求。
4.创建服务器
req请求对象:
只要服务器接收到客户端的请求,就会调用通过server.on()为服务器绑定的request事件处理函数
如果想在事件处理函数中,访问与客户端相关的数据和属性,可以使用如下的方式:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 
 | server.on("request",(req,res)=>{
 console.log("Someone visvit the server!");
 
 
 
 
 
 
 
 const url = req.url;
 const method = req.method;
 const str = `Your request url is ${url} and method is ${method}`;
 console.log(str);
 
 });
 
 | 
res响应对象:
在服务器的request事件处理函数中,如果想访问与服务器相关的数据或属性,可以使用如下方式:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 
 | server.on("request",(req,res)=>{
 console.log("Someone visvit the server!");
 
 
 
 
 
 
 
 const url = req.url;
 const method = req.method;
 const str = `Your request url is ${url} and method is ${method}`;
 console.log(str);
 
 
 
 
 
 
 
 
 res.end(str);
 
 });
 
 | 
解决中文乱码问题
当调用res.end()方法,向客户端发送中文内容的时候,会出现中文乱码问题,此时,需要手动设置内容的编码格式:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 
 | server.on("request",(req,res)=>{
 console.log("Someone visvit the server!");
 
 
 
 
 
 
 
 const url = req.url;
 const method = req.method;
 const str = `你请求的url地址是 ${url},请求的method类型是 ${method}`;
 
 res.setHeader("Content-Type","text/html;charset=utf-8");
 
 
 
 
 
 
 
 
 
 res.end(str);
 
 });
 
 | 
根据不同的url地址响应不同的html内容
核心步骤:
1.获取请求的url地址
2.设置默认的响应内容为404 Not Found
3.判断用户请求的是为/或/indexhtml首页
4.判断用户请求是否为/或about.html关于页面
5.设置Content-Type响应头,防止中文乱码
6.使用res.end把内容响应给客户端
实例:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 
 | const http = require("http");
 const server = http.createServer();
 
 server.on("request",(req,res)=>{
 
 const url = req.url;
 
 let responseText = "404 Not Found";
 
 
 
 if(url === "/" || url === "/index.html"){
 responseText = "<h1>这是首页</h1>";
 }else if(url === "/about.html"){
 responseText = "<h1>这是关于页面</h1>";
 }
 
 res.setHeader("Content-Type","text/html;charset=utf-8");
 
 res.end(responseText);
 });
 
 
 server.listen(8080,() => {
 console.log("Http serve running at http://127.0.0.1:8080");
 })
 
 
 |