Node.js http模块的使用,写一个最基本的服务器

105 阅读1分钟

代码:

// 导入http模块
const http = require('http')
// 导入fs模块
const fs = require('fs')
// 导入path模块
const path = require('path')

// 创建web服务器实例
const server = http.createServer()
// 为服务器绑定request事件,监听客户端请求
server.on('request', (req, res) => {
    // 设置响应头
    res.setHeader('content-type', 'text/html;charset=utf-8')
    // 从请求中获取url、method
    const {
        url,
        method
    } = req;
    // 定义一个路劲空串
    let fPath = ''
    // 判断拼接路径
    switch (url) {
        case "/":
            fPath = path.join(__dirname, './clock/index.html')
            break;
        default:
            fPath = path.join(__dirname, './clock', url)
            break;
    }
    // 读取文件,并根据读取结果进行响应
    fs.readFile(fPath, 'utf-8', (err, dataStr) => {
        if (err) return res.end('<h1>404 您访问的页面不存在</h1>')
        res.end(dataStr)
    })
})
// 启动在80端口
server.listen('80', () => {
    console.log('服务器启动成功!');
})

结果:

image-20220122223531811