1、导入 http 模块
// 1、导入http模块
const http = require('http')
2、创建 web 服务器实例
// 2、创建web服务器实例
const server = http.createServer()
3、为服务器实例绑定 request 事件,监听客户端的请求
// 3、为服务器绑定request事件
server.on('request',(req,res)=>{
// req.url 获取请求地址 默认是/
const url = req.url
console.log(url);
// req.method 获取请求的方式 get/post
const method = req.method
console.log(method);
// res.end() 服务器向客户端响应内容 暂不支持中文
res.end('Hello world!')
})
4、 启动服务器
// 4 、启动服务器
server.listen(80,()=>{
console.log('server running at http://localhost');
})
运行结果示意
安装配置NodeJs环境
如若想实现上述功能,首先需要安装配置NodeJs环境,我把链接放在这里,请前往菜鸟教程去看具体的教程,这里我就不多做赘述了。