Node.js_ express.Router 路由器_模块化管理路由
路由器 express.Router
路由器 模块化管理 路由
- 基本使用:
- 路由模块
1. 引入 express
const express = require('express');
其他相关模块
const sha1 = require('sha1');
const tableModel= require('models');
const {resolve} = require(path);
2. 创建路由器对象
const router = new express.Router();
3. 写 router.post() 或者 router.get()
4. 暴露本模块的路由
module.exports = router;
- index.js 主模块使用 app.use(中间件) 使用
1. 引入路由器模块
const uiRouter = require('./routers/uiRouter');
const userRouter = require('./routers/userRouter');
2. 应用路由器
app.use(uiRouter);
app.use(userRouter);
- 源代码实例(登录/注册)
package.json
{
"name": "node_express",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"express": "^4.16.4",
"mongoose": "^5.4.0"
}
}
templates/login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>用户登录</title> <link rel="stylesheet" type="text/css" href="css/index.css"/>
</head> <body>
<div id="outer_box" class="login">
<h2>用户登录</h2>
<form action="http://localhost:3000/login" method="post">
<div class="clothes">
<label for="input_name">用 户 名</label>
<input id="input_name" type="text" name="user_name" placeholder="请输入用户名" />
</div> <div class="clothes">
<label for="input_pwd">密 码</label>
<input id="input_pwd" type="password" name="user_pwd" placeholder="请输入密码" />
</div> <div class="clothes">
<a class="btn" href="http://localhost:3000/register">
<button type="button">注册</button>
</a>
<button class="login btn" type="submit">登录</button>
</div>
</form>
</div>
</body>
</html>
templates/register.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>用户注册</title> <link rel="stylesheet" type="text/css" href="css/index.css"/>
</head> <body>
<div id="outer_box" class="register">
<h2>用户注册</h2>
<form action="http://localhost:3000/register" method="post">
<div class="clothes">
<label for="input_name">用 户 名</label>
<input id="input_name" type="text" name="user_name" placeholder="请输入用户名" />
</div> <div class="clothes">
<label for="input_pwd">密 码</label>
<input id="input_pwd" type="password" name="user_pwd" placeholder="请输入密码" />
</div> <div class="clothes">
<label for="input_repeat_pwd">确认密码</label>
<input id="input_repeat_pwd" type="password" name="user_repeat_pwd" placeholder="请再次输入密码" />
</div> <div class="clothes">
<label for="input_email">注册邮箱</label>
<input id="input_email" type="text" name="user_email" placeholder="请输入邮箱地址" />
</div> <div class="clothes">
<button class="register btn" type="submit">注册</button>
<a class="btn" href="http://localhost:3000/login">
<button type="button">登录</button>
</a>
</div>
</form>
</div>
</body>
</html>
templates/css/index.css
body {
width: 100%;
height: 100%; color: #000;
background: #b9c2a4;
background-size: cover; /* 指定背景图片大小 */
} /*************************************************/
#outer_box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #1a45c3;
} #outer_box.login {
color: #9e098b;
} #outer_box.register {
color: #1a45c3;
} #outer_box>h2{
padding-bottom: 40px;
margin-left: -50px;
} .clothes {
width: 260px;
display: flex;
justify-content: space-between;
margin: 20px 0;
font-size: 18px;
line-height: 32px;
} .clothes>label{
width: 80px;
text-align: center;
} .clothes>input{
width: 170px;
height: 32px;
} button {
width: 100%;
height: 100%; font-size: 16px;
background-color: #c4ceda;
cursor: pointer;
} .clothes .btn{
width: 64px;
height: 32px;
margin: 0 20px;
} .clothes button.register{
background-color: #1a45c3;
color: #fff;
} .clothes button.login{
background-color: #9e098b;
color: #fff;
}
routers/get/index_router.js
const express = require('express');
const {resolve} = require('path'); const indexRouter = new express.Router(); /************************ get ***********************/
indexRouter.get('/', (request, response)=>{
response.sendFile(resolve(__dirname, '../../templates/login.html'));
}); indexRouter.get('/login', (request, response)=>{
response.sendFile(resolve(__dirname, '../../templates/login.html'));
}); indexRouter.get('/register', (request, response)=>{
response.sendFile(resolve(__dirname, '../../templates/register.html'));
}); module.exports = indexRouter;
routers/post/form_router.js
const express = require('express');
const sha1 = require('sha1'); const promiseConnect = require('../../db/connectDB.js');
const userInfoModel = require('../../models/userModel.js'); const formRouter = new express.Router(); /************************ post ***********************/
let logged = false ;
promiseConnect.then(async result=>{
console.log(result); formRouter.post('/register', async (request, response)=>{
const {
user_name:uName,
user_pwd:uPwd,
user_repeat_pwd:urePwd,
user_email:uEmail,
} = request.body; /**** 解构赋值 ****/ userInfo = {
"userName": uName,
"userPassword": uPwd,
"userEmail": uEmail
}; let errInfo = {}; if(urePwd !== uPwd){
errInfo.repeatPassword = '两次输入不一致';
};
if(!(/^[a-zA-Z][a-zA-Z0-9_]{5,20}$/.test(uName))){
errInfo.name = '用户名不合法';
};
if(!(/^[a-zA-Z0-9_]{6,20}$/.test(uPwd))){
errInfo.password = '密码不合法';
};
if(!(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(uEmail))){
errInfo.email = '邮箱不合法';
}; const badEmail = await userInfoModel.findOne({"userEmail": uEmail});
if(badEmail){
errInfo.emailRegistered = '邮箱已被注册';
}; if(errInfo.repeatPassword || errInfo.name || errInfo.password || errInfo.email){
response.send(errInfo);
return;
}; const fond = await userInfoModel.findOne({"userName": uName});
if(fond){
response.send({"error":'用户名已被注册'});
}else{
userInfo.userPassword = sha1(userInfo.userPassword);
await userInfoModel.create(userInfo);
response.redirect('/login'); // http://localhost:3000/login
};
}); formRouter.post('/login',async (request, response)=>{
logged = false;
let uName = request.body['user_name'];
let uPwd = request.body['user_pwd'];
userInfo = {
"userName": uName,
"userPassword": uPwd
}; if(!(/^[a-zA-Z][a-zA-Z0-9_]{5,20}$/.test(uName))){
logged = false; // 用户名不存在
}else if(!(/^[a-zA-Z0-9_]{6,20}$/.test(uPwd))){
logged = false; // 密码错误
}; const findName = await userInfoModel.findOne({"userName": uName});
const findPwd = await userInfoModel.findOne({"userPassword": sha1(uPwd)});
if(findName && findPwd){
logged = true;
}; response.send(logged?{"success":'登录成功'}:{"error":'用户名或密码错误'});
});
}).catch(err=>console.log(err)); module.exports = formRouter;
db/connectDB.js
const mongoose = require('mongoose'); module.exports = new Promise((resolve, reject)=>{
mongoose.connect('mongodb://localhost:27017/user_database', {useNewUrlParser:true})
mongoose.connection.once('open', err=>{
if(err){
console.log(err);
reject(err);
}else{
resolve('数据库已连接');
};
});
});
models/userModel.js
const mongoose = require('mongoose'); const Schema = mongoose.Schema;
const fieldSchema = new Schema({
"userName": {
"type": String,
"unique": true,
"required": true
},
"userPassword": {
"type": String,
"required": true
},
"userEmail": {
"type": String,
"unique": true,
"required": true
},
"createTime": {
"type": Date,
"default": Date.now()
}
}); module.exports = mongoose.model("user_info", fieldSchema);
index.js
const express = require('express'); const app = express(); const indexRouter = require('./routers/get/index_router.js');
const formRouter = require('./routers/post/form_router.js'); /*********************** 中间件 **********************/
// 暴露路由 login.html register.html
app.use(express.static('templates')); // 默认调用 next(); // 将 用户输入的数据 挂载到 请求体 request.body 上
app.use(express.urlencoded({extended: true})); // 默认调用 next(); app.use(indexRouter);
app.use(formRouter); /**************** 端口号 3000, 启动服务器 ***************/
app.listen(3000, err=>console.log(err?err:'\n\n服务器已启动: http://localhost:3000\nHunting Happy!'));
Node.js_ express.Router 路由器_模块化管理路由的更多相关文章
- node.js+express+jade系列二:rotue路由的配置
页面的访问最常见的是get和post两种,无论是get请求还是post请求express自动判断执行app.get或app.post 1:app.get(名称,路径)或app["get&qu ...
- Node.js使用Express.Router
在实际开发中通常有几十甚至上百的路由,都写在 index.js 既臃肿又不好维护,这时可以使用 express.Router 实现更优雅的路由解决方案. 目录结构如下: routes的index.js ...
- Node.js + Express 接口请求(GET、POST、PUT)事例
路由 路由是指应用程序的端点(URI)如何响应客户端请求.有关路由的介绍,请参阅基本路由. 您可以使用Express app对象的方法定义路由,这些方法对应于HTTP方法; 例如,app.get()处 ...
- express.Router
[express.Router] 1.可使用 express.Router 类创建模块化.可挂载的路由句柄.Router 实例是一个完整的中间件和路由系统,因此常称其为一个 “mini-app”. 下 ...
- express 学习笔记(一)路由
先导入express: var express = require('express'); var app = express(); 1.路由方法: get, post, put, head, del ...
- express.Router创建模块化路由
使用 app.route() 创建路由路径的链式路由句柄.由于路径在一个地方指定,这样做有助于创建模块化的路由,而且减少了代码冗余和拼写错误. 先放小实例: app.js var express = ...
- Node 之 Express 学习笔记 第二篇 Express 4x 骨架详解
周末,没事就来公司加班继续研究一下Express ,这也许也是单身狗的生活吧. 1.目录结构: bin, 存放启动项目的脚本文件 node_modules, 项目所有依赖的库,以及存放 package ...
- node+pm2+express+mysql+sequelize来搭建网站和写接口
前面的话:在这里已经提到了安装node的方法,node是自带npm的.我在技术中会用es6去编写,然后下面会分别介绍node.pm2.express.mysql.sequelize.有少部分是摘抄大佬 ...
- Node 之 Express 4x 骨架详解
周末,没事就来公司加班继续研究一下Express ,这也许也是单身狗的生活吧. 1.目录结构: bin, 存放启动项目的脚本文件 node_modules, 项目所有依赖的库,以及存放 package ...
随机推荐
- [物理学与PDEs]第2章习题4 习题 3 的变分
设 ${\bf u}$ 为满足第 3 题中条件的解. 证明 ${\bf u}$ 为如下变分问题 $$\bex \min_{{\bf w}\in A}\cfrac{1}{2}\int_\Omega |{ ...
- [物理学与PDEs]第2章习题2 质量力有势时的能量方程
试证明: 如果质量力有势, 即存在 $\phi$ 使 ${\bf F}=-\n \phi$, 那么理想流体的能量守恒方程的微分形式可写为 $$\bex \cfrac{\rd}{\rd t}\sex{e ...
- bilibili存储型xss (绕过长度限制打乱顺序限制)
在个人空间的我的收藏中可编辑视频收藏的名称,之后尝试写入标签. http://space.bilibili.com/ 发现输出到前端的尖括号被转义了,不过出现了一个json接口,他的Content-T ...
- PERFECT NUMBER PROBLEM(思维)
题目链接:https://nanti.jisuanke.com/t/38220 题目大意:这道题让我们判断给定数字是否为完美数字,并给来完美数字的定义,就是一个整数等于除其自身之外的所有的因子之和. ...
- 410 for 循环 运算 改变循环的控制流 死循环 遍历数组 定义方法 有名函数匿名函数 定义函数的方法取值 date math 局部变量 函数 局部与全局变量 次幂/随机数/取绝对值/向上取整/平方根
for(1.表达式1;2.表达式2;3.表达式3){ 4.循环体语句; } 先执行1 ,在执行2, 表达式, 如果2结果为false,退出循环 如果2是true 执行4 在执行3 执行2 举例打印1- ...
- WPS或xls 数据分列 清洗
一 .一般分离 时间:2017年11月27日14:55:12 数据如下: 501陈**:田莨铺58 502陈**:田莨铺58 503陈**.六麻杨冲58元 504陈**.石脚哗.200元 505陈** ...
- 将.NET Core部署在Docker
转载自:ASP.NET Core 2.1 使用Docker运行 1.新建ASP.NET Core项目 新建一个名为“DockerSample”的ASP.NET Core项目 运行程序,页面如下: 2. ...
- H - 栀子花开
这是一个栀子花开的季节,也是一个离别的季节,四年一千多个日日夜夜,那校园的角角落落,留下了我们沉思的身影:那上百次的成绩排名表,印证了我们深深浅浅不断进步的轨迹,但是这些进步都离不开老师的谆谆教诲. ...
- noj算法 踩气球 回溯法
描述: 六一儿童节,小朋友们做踩气球游戏,气球的编号是1-100,两位小朋友各踩了一些气球,要求他们报出自己所踩气球的编号的乘积.现在需要你编一个程序来判断他们的胜负,判断的规则是这样的:如果两人都说 ...
- oracle 列行转换
1.列转换 1:每个字母转成一行 SELECT SUBSTR(A.COLUMN1, LEV, 1) COLUMN1FROM ( SELECT 'AABDC' COLUMN1 FROM DUA ...