express 和 node 我就不介绍了因为我也不知道怎么介绍,别问,问就是不知道
1、创建项目,淘宝镜像自己搞一下
mkdir dh-express
cd dh-express
cnpm init -y
2、自行安装如下的东西
"body-parser": "^1.19.0",
"boom": "^7.3.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"express-jwt": "^5.3.1",
"jsonwebtoken": "^8.5.1",
"md5": "^2.2.1",
"mysql": "^2.18.1",
"nodemon": "^2.0.3"
3、创建 app.js
const express = require('express')
const router = require('./router')
const bodyParser = require('body-parser')
const cors = require('cors')
// 创建 express 应用
const app = express()
app.use(cors()) // 跨域用的
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use('/', router)
// 使 express 监听 9000 端口号发起的 http 请求
const server = app.listen(9000, function() {
const { address, port } = server.address()
console.log('Http Server is running on http://localhost:9000', address, port)
})
4、自行以下概念express基础概念: 中间件、路由、异常处理
5、package.json
{
"name": "express",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon app.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"boom": "^7.3.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"express-jwt": "^5.3.1",
"jsonwebtoken": "^8.5.1",
"md5": "^2.2.1",
"mysql": "^2.18.1",
"nodemon": "^2.0.3"
}
}
6、nodemon.json 它的作用是监听代码文件的变动,当代码改变之后,自动重启。
{
"restartable": "rs",
"ignore": [
".git",
".svn",
"node_modules/**/node_modules"
],
"verbose": true,
"execMap": {
"js": "node --harmony"
},
"watch": [],
"env": {
"NODE_ENV": "development"
},
"ext": "js json"
}
7、创建 db 目录,新建两个文件:
config.js数据库的配置:
module.exports = {
host: 'localhost',
user: 'root',
password: '123456',
database:'test',
port: 5321,
multipleStatements: true//允许多条sql同时执行
}
index.js 操作数据库的方法
const mysql = require('mysql');
const config = require('./config');
function connect() {
return mysql.createConnection({
host: config.host,
user: config.user,
password: config.password,
database: config.database,
port: config.port,
multipleStatements: config.multipleStatements//允许多条sql同时执行
})
}
function querySql(sql) {
const conn = connect()
return new Promise((resolve, reject) => {
try {
conn.query(sql, (err, results) => {
if (err) {
reject(err)
} else {
resolve(results)
}
})
} catch (e) {
reject(e)
} finally {
conn.end()
}
})
}
module.exports = {
querySql
}
使用的方法就是
db.querySql('select * from order').then(res => {
console.log(res)
})
8、jwt 验证
一般我们实际开发中我们接口都要有个接口权限验证
我说一下我遇到过的token放在哪里了,我一般会放在sessionStorage,就是页面窗口会话的,打开别的窗口就获取不到了,如果你想打开别的窗口也可以获取到就用cookie 或者 localStorage,这个具体的区别我就不说了,还有一点是我遇到过的,后台帮你设置cookie,他们设置了http-only打了对勾,我们前端就不可以操作了,他们可以自己对比token变化哈哈,继续说jwt
module.exports = jwt({
secret: 'zidingyi', // 秘钥自定义
credentialsRequired: true
}).unless({
path: [
'/user/login' // 接口路由白名单不用做权限验证
]
})
怎么使用作为中间件使用比如
const express = require('express')
const jwt = require('./jwt')
const router = express.Router()
router.use(jwt)