服务器端代码app.js如下:
//引入系统模块http
//创建网站服务器
//为网站服务器对象添加请求事件
//实现路由功能
//1.获取客户端的请求方式
//2.获取客户端的请求地址
const http=require('http');
const app=http.createServer();
const url=require('url');
app.on('request',(req,res)=>{
//1.获取请求方式
//req.method(method不是方法,是属性)得到的是大写的GET或POST。因此要转换成小写。
const method=req.method.toLowerCase();
//2.获取请求地址
//req.url是请求的url,而url.parse来获取url的各个部分,pathname是获得请求地址
const pathname=url.parse(req.url).pathname;
//响应头的设置解决中文乱码问题。
res.writeHead(200,{
'content-type':'text/html;charset=utf-8'
});
//3.响应主体内容
if(method=='get'){
if(pathname=='/'||pathname=='/index'){
res.end('欢迎来到首页');
}else if(pathname=='/list'){
res.end('欢迎来到列表页');
}else{
res.end('您访问的页面未找到');
}
}else if(method=='post'){
//post里面内容和get基本类似一样
}
});
//4.监听端口
app.listen(3000);
console.log('服务器启动成功');
启动服务器:
测试结果: