切换导航
简历
工具
演示
查询
导航菜单
服务端
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] ### Node.js动态网站开发 #### 1. 参数传递与获取 ##### 1.1 get参数处理 + 获取地址对象信息`url.parse` + 第一个参数:地址 + 第二参数:parseQueryString:默认为false,如果设置为true,则输出的对象中query属性为一个对象(参数对象) + 第三参数:slashesDenoteHost:默认为false,如果设置为true,地址是以`//`开始的话,slashes=true,host=域名,hostname=域名(host,hostname = `//`之后到第一个`/`货`?`之前这段字符串) ```js const url = require("url") let urlAdrr = "http://www.cylyccjy.com/blog/info-md.html/2ECFFD3C750C8A74?type=195" let urlObj = url.parse(urlAdrr) console.log(urlObj) ``` >输出 ```json Url { protocol: 'http:', //请求协议 slashes: true, //是否有双斜杠// auth: null, //地址带有账户密码验证信息例如:http://user:pass@cylyccjy.com host: 'www.cylyccjy.com', //域名包含指定的端口 port: null, //端口 hostname: 'www.cylyccjy.com', //域名不包含指定的端口 hash: null, //地址#符合后面的字串 search: '?type=195', //地址参数?之后的字串 query: 'type=195', //search去除?后,后面的字串 // query: [Object: null prototype] { type: '195' }, //url.parse第二个参数设置为true pathname: '/blog/info-md.html/2ECFFD3C750C8A74', //路径?前到域名后这部分的字串 path: '/blog/info-md.html/2ECFFD3C750C8A74?type=195', //包括参数和路径 href: 'http://www.cylyccjy.com/blog/info-md.html/2ECFFD3C750C8A74?type=195' } ``` + 将地址对象转换为字符串`url.format`(新版本已弃用) ```js const url = require("url") let obj = { protocol: 'http:', //请求协议 slashes: true, //是否有双斜杠// auth: null, //地址带有账户密码验证信息例如:http://user:pass@cylyccjy.com host: 'www.cylyccjy.com', //域名包含指定的端口 port: null, //端口 hostname: 'www.cylyccjy.com', //域名不包含指定的端口 hash: null, //地址#符合后面的字串 search: '?type=195', //地址参数?之后的字串 query: 'type=195', //search去除?后,后面的字串 // query: [Object: null prototype] { type: '195' }, //url.parse第二个参数设置为true pathname: '/blog/info-md.html/2ECFFD3C750C8A74', //路径?前到域名后这部分的字串 path: '/blog/info-md.html/2ECFFD3C750C8A74?type=195', //包括参数和路径 href: 'http://www.cylyccjy.com/blog/info-md.html/2ECFFD3C750C8A74?type=195' } console.log(url.format(obj)) //输出:http://www.cylyccjy.com/blog/info-md.html/2ECFFD3C750C8A74?type=195 ``` + 获取浏览器请求地址参数 请求地址为 http://10.10.0.**:***/index.html?username=%E5%AD%9F%E5%BE%B7&password=123123 ```js const paths = require("path") const http = require("http") const url = require('url') http.createServer((req, res) => { let obj = url.parse(req.url, true) res.writeHead(200, { "content-type": "text/html;charset=utf8" }) res.write(obj.query.username) res.write("<br/>") res.write(obj.query.password) res.end() }).listen(3111, '1.1.**.***",', () => { console.log("服务已启动") }) // 输出 // 孟德 // 123123 ``` ##### 1.2. post参数处理 + 将地址参数字符串转换为对象 `queryString.parse` - 如果地址字符串参数名称一致,则会将名称一致的参数值放到一个数组中 ```js const queryString = require('querystring') let param = "username=孟德&password=123123" let obj = queryString.parse(param) console.log(obj) //输出:[Object: null prototype] { username: '孟德', password: '123123' } //将上面的param参数修改为下面的字串 //let param = "username=孟德&password=123123&username=刘备" //输出:[Object: null prototype] { // username: [ '孟德', '刘备' ], // password: '123123' //} ``` + 将对象转化为地址参数格式 `queryString.stringify` ```js const queryString = require('querystring') let obj = { username: ['孟德', '刘备'], password: '123123' } let param = queryString.stringify(obj) console.log(queryString.unescape(param)) //输出:username=孟德&username=刘备&password=123123 ``` + 将字符串进行转码`queryString.escape` ```js let str = "username=孟德&username=刘备&password=123123" console.log(queryString.unescape(str)) //输出:username%3D%E5%AD%9F%E5%BE%B7%26username%3D%E5%88%98%E5%A4%87%26password%3D123123 ``` + 将字符串进行解码`queryString.unescape` ```js let str = "username=%E5%AD%9F%E5%BE%B7&username=%E5%88%98%E5%A4%87&password=123123" console.log(queryString.unescape(str)) //输出:username=孟德&username=刘备&password=123123 ``` + 获取post请求参数 这里运用到了两个新的事件,数据传输中事件`data`和数据传输结束`end` ```js const http = require("http") const queryString = require('querystring') http.createServer((req, res) => { let reData = ""; req.on("data", (chunk) => { reData += chunk }) req.on("end", () => { let obj = queryString.parse(reData) res.writeHead(200, { "content-type": "text/html;charset=utf8" }) res.write(obj.username) res.write("<br/>") res.write(obj.password) res.end() }) }).listen(3111, '10.10.*.***', () => { console.log("服务已启动") }) ``` #### 2. 一个动态网站开发示例 按下面代码部署后,访问地址:http://localhost:3000/query.html ##### 2.1 nodejs服务代码 case.js ```js const paths = require("path") const fs = require("fs") const http = require("http") const querystrings = require("querystring") //数据源 const sanguo = require("../00-data/sanguo.json") http.createServer((req, res) => { let url = paths.join(__dirname, "../00-tpl", req.url) let dtype = "text/plain;charset=utf8" let stateCode = 200 //查询页面 if (req.url.startsWith("/query") && req.method == "GET") { dtype = "text/html;charset=utf8" fs.readFile(url, "utf8", (err, data) => { if (err) { res.writeHead(500, { "content-type": dtype }) res.end("server error") } else { res.writeHead(stateCode, { "content-type": dtype }) res.end(data); } }) } //提交查询页面 else if (req.url.startsWith("/backInfo") && req.method == "POST") { let reData = ""; req.on("data", (chunk) => { reData += chunk }) req.on("end", () => { //获取浏览器提交的数据 let obj = querystrings.parse(reData) let info = null; //匹配提交结果 sanguo.forEach(element => { if (element.username == obj.username) { info = element } }); if (sanguo != undefined && info != null && info != undefined) { dtype = "text/html;charset=utf8" res.writeHead(stateCode, { "content-type": dtype }) //读取模板文件替换匹配的数据 fs.readFile(url, "utf8", (err, data) => { if (err) { res.writeHead(500, { "content-type": dtype }) res.end("server error") } else { res.writeHead(stateCode, { "content-type": dtype }) data = data.replace("$$${username}$$$", info.username) .replace("$$${usersex}$$$", info.usersex) .replace("$$${userposition}$$$", info.userposition). replace("$$${useradrr}$$$", info.useradrr) res.end(data); } }) } else { res.writeHead(500, { "content-type": dtype }) res.end("未找到对应的信息") } }) } }).listen(3000, '192.168.31.238', () => { console.log("服务已启动") }) ``` ##### 2.2 模板文件一 query.html ```html <html> <head> <meta charset="utf-8"> <!-- <meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1.0, maximun-scale=1.0, minimun-scale=1.0"> --> </head> <div id="app"> <form action="http://192.168.**.***:3000/backInfo.html" method="POST" enctype="application/x-www-form-urlencoded"> 姓名 <input type="text" name="username"> <br /> <button type="submit">提交</button> </form> </div> <script type="text/javascript"> </script> </html> ``` ##### 2.3 模板文件二 backInfo.html ```html <html> <head> <meta charset="utf-8"> <!-- <meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1.0, maximun-scale=1.0, minimun-scale=1.0"> --> </head> <div id="app"> <ul> <li> 姓名:$$${username}$$$ </li> <li> 性别:$$${usersex}$$$ </li> <li> 职位:$$${userposition}$$$ </li> <li> 地址:$$${useradrr}$$$ </li> </ul> </div> <script type="text/javascript"> </script> </html> ``` ##### 2.4 数据源 sunguo.json ```json [ { "username": "曹操", "usersex": "男", "userposition": "王", "useradrr": "魏" }, { "username": "关羽", "usersex": "男", "userposition": "将", "useradrr": "蜀" }, { "username": "周瑜", "usersex": "男", "userposition": "帅", "useradrr": "吴" } ] ``` ### 可绑定事件 #### 1. data数据传输中事件 回调函数中chunk参数是数据接收中的内容,data不是一次接收完成的。 #### 2. end数据传输结束事件 请求数据全部接收完成后触发
扫一扫手机看
点击排行
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缓存问题导致数据不更新的解决办法
订阅号