/**
* 目标: 基于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
相关推荐
掘金者阿豪2 小时前
SQL Server数据迁移完成后,凌晨的数据库告警该怎么查?JudithHuang2 小时前
React 嵌套路由与布局htzyl2062 小时前
前端阶梯——第四十三章、实战二:待办清单To-Do摹客3 小时前
【3D设计】界面设计中的3D元素:应用场景+5款工具横评(含Three.js)Hilaku3 小时前
CORS 到底在保护谁?90% 的前端理解错了跨域的本质wno7043 小时前
node.js中使用jquery阿琳a_4 小时前
b-map-viewer:面向 Vue 3 的地图可视化 SDK,从接入到展示再到交互分析10年前端老司机4 小时前
Agent 商业化困局:热闹的发布会,冷清的付费客户钱栈up4 小时前
热榜上手|HyperFrames:写HTML出MP4