![]()
# Express 创建本地服务器
# 创建 express 文件夹
# 初始化项目文档
# 创建项目入口文件 app.js
1 2 3 4 5 6 7 8 9
| const express = require('express') const app=express() app.listen(8081,()=>{ console.log('端口运行在8081'); })
|
# 创建 db 文件夹添加 mysql.js 作为 sql 配置文件
1 2 3 4 5 6 7 8 9
| const mysql = require('mysql') const db = mysql.createPool({ host: '127.0.0.1',//本机ip地址相当于localhost user: 'root', password: '123123', database: 'new_schema' }) module.exports = db
|
# 创建路由文件夹,以功能名命名 js 文件 xxx.js
1 2 3 4 5 6 7 8 9 10
| const express=require('express') const router=express.Router()
const {cha}=require('../router_handler/article_handler')
router.get('/midsen',验证规则,cha)
module.exports = router
|
# 创建路由处理回调函数文件夹,以 handler 命名法,作为对应路由的数据处理文件
1 2 3 4 5 6
| const db = require('../db/mysql') exports.cha = (req, res) => { res.send('ok') }
|
# 导入 nodemon 保存自动重启
1
| npm i nodemon --save-dev
|
# 启动服务
在浏览器中 8081 端口添加 /article/midsen:
# 下面就可以通过 req.query/req.body 来拿到从用户端传过来的请求数据,db.query 操作数据库通过 res.send,把数据传回客户端
1 2 3 4 5 6 7 8 9 10 11
| const selSql = 'select id,username,user_pic,nickname from ev_users where id=?' db.query(selSql, req.auth.id, (err, result) => { if (err) return res.cc(err.sqlMessage) if (result.length !== 1) return res.cc('获取信息失败') res.send({ status: 0, message: '获取信息成功', data: result[0] }) })
|
回传数据
定义全局中间件错误处理函数
1 2 3 4 5 6 7 8 9 10
| app.use((req, res, next) => { res.cc = function(err, status = 1) { res.send({ status, message: err instanceof Error ? err.message : err }) } next() })
|
# 定义数据验证规则,用于验证用户发送数据是否合法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const joi = require('joi') const title = joi.string().min(1).max(30).required() const cate_id = joi.number().integer().min(1).required() const content = joi.string().min(1).max(255).required() const cover_img = joi.string().dataUri().required() const state = joi.string().pattern(/[发布]|[草稿]/).required() module.exports.add_atricle_schema = { body: { title, cate_id, content, cover_img, state } }
|
# 定义全局中间件错误验证处理中间件
1 2 3 4 5 6 7 8 9
| app.use((err, req, res, next) => { if (err instanceof Joi.ValidationError) return res.cc(err) if (err.name === 'UnauthorizedError') return res.cc("身份认证失败") res.cc(err) })
|
# 引入全局处理中间件和验证规则解构
1 2 3 4 5 6 7 8 9 10 11 12
| const expressJoi = require('@escook/express-joi') const { reg_login_schema } = require('../schema/user') router.post('/reguser', expressJoi(reg_login_schema), handler.regUser) router.post('/login', expressJoi(reg_login_schema), handler.loGin) module.exports = router
|
# 添加用户登录 token 密钥
1 2 3 4 5 6 7 8 9 10 11
| const bcry = require('bcryptjs') const jsonScr = require('jsonwebtoken') const scritKey = require('../Config') user.password = bcry.hashSync(user.password, 10)
|
# token 密钥规则
1 2 3 4 5 6
| module.exports = { jwtScecret: 'mmws ^^', expiresIn: '10H' }
|
# 获取用户信息时验证密钥身份
1 2
| const compare = bcry.compareSync(req.body.oldPwd, result[0].password) if (!compare) return res.cc("旧密码不正确")
|
res.cc 是全局 res.send 中间件