根据不同的url响应客户端的内容
const http = require('http')
// **1. 导入http模块**
// **2. 创建web服务器实例**
const server = http.createServer()
// **3. 为服务器实例绑定request事件,监听客户端的请求**
server.on('request', (req, res) => {
//获取请求的url地址
const url = req.url
//设置默认的响应内容为404 not found
let content = '<h1>404 not found</h1>'
//判断用户的请求是否为 /或者index.html首页
//判断用户的请求是否为 /about.html
if (url == '/' || url == '/index.html') {
content = '<h1>首页</h1>'
} else if (url == '/about.html') {
content = '<h1>关于</h1>'
}
//设置 Content-type 响应头,防止中文乱码
res.setHeader('Content-Type', 'text/html;charset=utf-8')
//使用res.end()把内容响应给客户端
res.end(content)
})
server.listen(80, () => {
console.log('server running at http://127.0.0.1')
})