- 核心步骤:
- 获取请求的url
- 设置默认的响应内容为404 Not found
- 判断用户请求是否是 / 或者 /index.html
- 判断用户请求的是否是/about.htm
- 设置 Content-Type响应头,防止中文乱码
- 使用res.end()把响应内容发送给客户端
使用了 let 声明的变量只在 let 命令所在的代码块内有效
它声明的变量作用域只在判断体内,判断外的变量不受影响。
const http=require("http");
const server=http.createServer();
//req是请求对象,包含了与客户端相关的属性和数据
server.on('request',function(req,res){
const url =req.url;//获取请求的url地址 这是客户端输入的
//let 声明的变量只在 let 命令所在的代码块内有效
let content='<h1>404 Not found</h1>';
if(url==='/'||url==='/index.html'){
content='<h1>首页</h1>';
}else if(url=='/a.html'){
content='<h1>a页面</h1>';
}
//req.method是客户端请求的method类型
const method =req.method;
const str=`您请求的url地址是 ${url},请求的method类型是 ${method}`;
console.log(str);
//设置响应头Content-Type的值为text/html; charset=utf-8
res.setHeader('Content-Type','text/html; charset=utf-8');
//调用res.end向客户端响应内容
res.end(content);
}
)
server.listen(80,function(){
console.log('服务器启动成功 at http://127.0.0.1')
})