/**
* 目标: 基于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端口请求成功');
})
http模块 - 创建Web服务以及案例
怕冷的火焰(~杰)2024-09-07 9:54
相关推荐
C2X1 分钟前
Vue3.0 学习总结汤姆Tom3 分钟前
CSS 新特性与未来趋势尘世中一位迷途小书童4 分钟前
🚀 pnpm + Monorepo 实战指南:现代前端项目管理的最佳实践杨超越luckly18 分钟前
HTML应用指南:利用GET请求获取全国中国建设银行网点位置信息王翼鹏19 分钟前
html 全角空格和半角空格敲代码的嘎仔20 分钟前
JavaWeb零基础学习Day2——JS & VueCsharpDev-奶豆哥23 分钟前
jq获取html字符串中的图片逐个修改并覆盖原html的解决方案IT_陈寒1 小时前
Python性能优化:用这5个鲜为人知的内置函数让你的代码提速50%简小瑞1 小时前
VSCode源码解密:一行代码解决内存泄漏难题邢行行1 小时前
Node.js 核心模块与模块化笔记