1 封装访问数据库、修改数据库相关配置
module.exports = {
query: function (sql, callback) {
const mysql = require('mysql');
const conn = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'l-ddui',
database : 'l-ddui'
});
conn.connect();
conn.query(sql, callback);
conn.end();
}
}
2 启用服务器
const express = require("express")
const server = express()
server.listen(10086, () => {
console.log("您的服务器已经在10086 端口就绪了");
})
3 cors 跨域设置
const cors = require('cors')
server.use(cors())
4 静态资源设置
server.use('/uploads',express.static('uploads'))
5 jwt 生成token
const tokenStr = jwt.sign({ name: username }, 'l-ddui', { expiresIn: 2 * 60 * 60 })
const token = 'Bearer ' + tokenStr
res.json({ "status": 0, "message": "登录成功!", token })
7 token 有效性检验
const jwt = require('express-jwt');
server.use(jwt({
secret: 'l-ddui',
algorithms: ['HS256']
}).unless({
path: ['/user/login', '/user/register', /^\/uploads\/.*/]
}));
8 错误中间件处理
server.use((err, req, res, next) => {
console.log('有错误', err)
if (err.name === 'UnauthorizedError') {
res.status(401).send({ code: 1, message: '身份认证失败!' });
}
});
9 注册路由
const userRouter = require('./router/user_router.js')
server.use('/hero', heroRouter)