1.引入模块http
const http=require('http')
2.创建一个http服务器
const server=http.createServer()
3. 绑定request事件,监听客户端请求
server.on('request', (req, res) => {
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>'
}
//设置请求头,防止乱码
res.setHeader('Content-Type', 'text/html; charset=utf-8')
//发送给客户端消息
res.end(content)
})
4.启动服务器,配置端口号
server.listen(8080, () => {
console.log('server running at http://localhost:8080')
})