切换导航
简历
工具
演示
查询
导航菜单
服务端
30
前端
114
数据库
82
进阶开发
8
桌面程序
2
QA
15
软件使用
36
规范协议
5
操作系统
11
AI
0
复用资源
6
硬件
0
标签
HTML
正则表达式
Json
包管理工具
vite
CSS
XPath
JavaScript
Jquery
less
ES6
Vue
React
vue 3
Layui
editor.md
sea.js
Zepto.js
mysql.js
mssql.js
NodeJs
Express
前端template
YAML
杂项
外部链接
.NET Core SDK和运行时安装包
淘宝 NPM 镜像
查询网
Tables Generator线上表格转换工具
引用cdn在线脚本和样式
首页
前端
nodeJs Web开发之搭建静态网站
[TOC] ## 创建Nodejs服务 ### 初步实现服务 + `http.createServer()` 创建服务器实例对象 + `http.listen()`监听可访问服务的端口 - 参数1:监听的端口 - 参数2:设置服务访问ip地址 - 参数3:回调函数,服务启动后执行 + `http.on()` 绑定事件函数,示例中绑定了一个[request](#h4-request-)请求事件 ```js const http = require('http') // //创建服务器实例对象 // let server = http.createServer(); // //绑定请求事件,req请求的信息,res响应的信息 // server.on("request", (req, res) => { // //设置头部信息。以下设置响应的状态码,和内容的编码方式 // res.writeHead(301, { "content-type": "text/html;charset=utf8" }) // res.end("你好!中国") // }) // //服务监听的端口 // server.listen(3000) //简写 http.createServer((req, res) => { //设置头部信息。以下设置响应的状态码,和内容的编码方式 res.writeHead(301, { "content-type": "text/html;charset=utf8" }) res.end("你好!中国") }).listen(3000, "192.168.**.***", () => { console.log("运行中……") }) ``` 服务启动后,使用快捷键`Ctrl + C`退出运行中的nodejs服务 ### 实现静态页面访问 运用nodejs的文件读取接口和服务接口实现访问静态页面的服务 ```js const http = require('http') const path = require('path') const fs = require('fs') let readFile = (htmlpath, res) => { fs.readFile(htmlpath, 'utf8', (err, data) => { if (err) { res.end("server error") } else { res.end(data) } }) } http.createServer((req, res) => { res.writeHead(200, { "content-type": "text/html;charset=utf8" }) if (req.url.startsWith("/index")) { readFile(path.join(__dirname, '../00-temp/index.html'), res) } else if (req.url.startsWith("/about")) { readFile(path.join(__dirname, '../00-temp/about.html'), res) } }).listen(3000, "192.168.**.***", () => { console.log("运行中……") }) ``` ### 优化完善静态页面访问 + 访问路径和静态文件完全匹配上可用,除html文件其它资源文件如图片,xml文件也需要名称一致才可访问,如果带有参数的路径需要再优化 + 引入的mine.json文件可在本站复用资源->[mine类型json格式](http://www.cylyccjy.com/blog/info-md.html/2ECFFD3C750C8A74?type=195)获得 ```js const paths = require("path") const fs = require("fs") const http = require("http") const mine = require("../../../data/mine.json") http.createServer((req, res) => { let url = paths.join(__dirname, "../../", req.url) let ext = paths.extname(url) let dtype = "text/plain" let stateCode = 200 if (ext) { ext = ext.slice(1, ext.length); let dtype = mine[ext]; if (dtype == undefined) { stateCode = 404 dtype = "text/plain;charset=utf8"; } else { if (dtype.startsWith("text")) { dtype += ";charset=utf8"; res.writeHead(stateCode, { "content-type": dtype }) } } res.writeHead(stateCode, { "content-type": dtype }) } else { dtype += ";charset=utf8"; res.writeHead(stateCode, { "content-type": dtype }) } fs.readFile(url, "utf8", (err, data) => { if (err) { res.end("server error") } else { res.end(data); } }) }).listen(3111, '10.10.**.***",', () => { console.log("服务已启动") }) ``` ### 访问静态页面主要代码模块化 使用`exports`将核心代码模块化,模块文件为`staticServer.js` ```js const fs = require('fs') const paths = require('path') const mine = require("../../../data/mine.json") // req请求对象 // res相应客户端对象 // root静态文件存放的根目录 exports.staticServer = (req, res, root) => { let url = paths.join(root, req.url) let ext = paths.extname(url) let dtype = "text/plain" let stateCode = 200 if (ext) { ext = ext.slice(1, ext.length); let dtype = mine[ext]; if (dtype == undefined) { stateCode = 404 dtype = "text/plain;charset=utf8"; } else { if (dtype.startsWith("text")) { dtype += ";charset=utf8"; res.writeHead(stateCode, { "content-type": dtype }) } } res.writeHead(stateCode, { "content-type": dtype }) } else { dtype += ";charset=utf8"; res.writeHead(stateCode, { "content-type": dtype }) } fs.readFile(url, "utf8", (err, data) => { if (err) { res.end("server error") } else { res.end(data); } }) } ``` 调用模块代码 ```js const paths = require("path") const http = require("http") //引入静态服务模块 const ss = require("./staticServer.js") http.createServer((req, res) => { let dirPath = paths.join(__dirname, "../../") ss.staticServer(req, res, dirPath) }).listen(3111, '10.10.**.***", () => { console.log("服务已启动") }) ``` ### 可绑定事件 #### request请求事件 回调函数两个参数请求信息参数req和响应信息参数res ##### 请求信息参数<mark>req</mark> req对象是http.IncomingMessage的实例对象 + `req.url` 获取URL中的访问路径,端口之后的部分。例如:<mark>'/index.html'</mark> ##### 响应信息参数<mark>res</mark> res对象是http.ServerResponse的实例对象 + `res.writeHead` 设置响应信息的头部信息,设置需要在写入返回信息之前,即需要在write和end之前 - 常用参数有:<mark>状态码</mark>,<mark>内容格式声明</mark> + `res.end` 响应返回的信息内容 - 常用参数:<mark>内容</mark>,<mark>编码方式</mark>,<mark>回到函数</mark> + `res.write` 给客户端返回添加内容,可以多次添加 - 常用参数:<mark>内容</mark>,<mark>编码方式</mark>,<mark>回到函数</mark> ##### 请求路径分发示例 ```js const http = require('http') http.createServer((req, res) => { //设置头部信息。以下设置响应的状态码,和内容的编码方式 res.writeHead(301, { "content-type": "text/html;charset=utf8" }) let content = ""; //判断路径分发请求 if (req.url.startsWith("/index.html")) { content = "首页"; } else if (req.url.startsWith("/about.html")) { content = "关于我们"; } else { res.write("欢迎") res.write("进入") content = "其他"; } res.end(content) }).listen(3000, "192.168.**.***", () => { console.log("运行中……") }) ```
扫一扫手机看
点击排行
windows 文件资源管理器使用
Layui 弹窗open使用说明
SQL Server 中字符串函数使用
C# 使用QQ邮箱代理做邮件接收功能
SQL Server关于apply的两种形式cross apply 和 outer apply
ASP.NET MVC 模型的自定义验证
nvm安装及常用命令
SQL Server 中数据类型转换
SQL Server 中WITH AS短语的使用
IE浏览器下AJAX缓存问题导致数据不更新的解决办法
订阅号