http模块 - 创建Web服务以及案例

复制代码
/**
 * 目标: 基于http模块创建Web服务程序
 *
 * 1.1 加载http模块, 创建Web服务对象
 * 1.2 监听request请求事件, 设置响应头和响应体
 * 1.3 配置端口号并启动Web服务
 * 1.4 浏览器请求: http://localhost:3000 测试
 *
 */

// 加载http模块, 创建web服务对象
const http = require('http');
const server = http.createServer()

// 监听request请求事件, 设置响应头和响应体
server.on('request', (req, res) => {
    // 设置响应头, 内容类型 - 普通文本以及中文编码格式
    res.setHeader('Content-Type', 'text/plain;charset=utf-8')

    // 设置响应体内容, 结束本次请求与响应
    res.end('欢迎使用Node.js 和http模块创建的Web服务')
})

// 配置端口号并启动Web服务
server.listen(4000, () => {
    console.log('启动成功');
})




// 案例 - 浏览压缩后的html页面
/**
 *
 * 目标: 基于Web服务, 开发提供网页资源的功能
 * 步骤:
 *  1. 基于http模块, 创建Web服务
 *  2. 使用req.url获取请求资源路径, 并读取index.html里字符串内容返回给请求方
 *  3. 其他路径, 暂时返回不存在提示
 *  4. 运行Web服务, 用浏览器发起请求
 *
 */
const fs = require('fs')
const path = require('path')
const http = require('http');
const server = http.createServer()
server.on('request', (req, res) => {
    if (req.url === '/index.html') {
        fs.readFile(path.join(__dirname, 'dist/index.html'), (err, data) => {
            if(err) console.error(err)
            else {
                res.setHeader('Content-Type', 'text/html;charset=utf-8');
                res.end(data.toString())
            }
        })
    } else {
        res.setHeader('Content-Type', 'text/html;charset=utf-8')
        res.end('你要访问的资源不存在')
    }
})

server.listen(3000, () => {
    console.log('3000端口请求成功');
})
相关推荐
崔庆才丨静觅9 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby606110 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了10 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅10 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅11 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅11 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment11 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅11 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊11 小时前
jwt介绍
前端
爱敲代码的小鱼11 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax