前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Node.js http模块的使用,写一个最基本的服务器

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

作者头像
倾盖
发布2022-08-16 14:34:13
3750
发布2022-08-16 14:34:13
举报
文章被收录于专栏:RivenCabinRivenCabin

代码:

代码语言:javascript
复制
// 导入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
image-20220122223531811
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档