本文属于搭建主要使用express框架搭建,有一定的express理解,本文只有登录、注册、获取用户详情的接口,同时使用apidoc生成文档,配合git看吧
node作为后端极少,一般作为简易的博客后端或者一些大公司作为产品的应用层做中转
1.首先你必须了解一些关于node的express的框架的整体架构.
官网express
2.首先直接安装
npm install -g express-generator
3.生成项目(–view主要是选用模板引擎,前后台分离不用)
express --view=pug 英文名称
4.安装必要的依赖
我这里直接复制了
"dependencies": {
"cheerio": "^1.0.0-rc.9",
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"jsonwebtoken": "^8.5.1",
"md5": "^2.2.1",
"morgan": "~1.9.1",
"mysql": "^2.17.1",
"node-rsa": "^1.0.7",
"pug": "2.0.0-beta11"
}
5.到这里就是先链接数据库
5.1.第一种封装(直接链接)
var mysql = require('mysql');
module.exports = (function(){
var pool = mysql.createPool({
host:'localhost',
user:'',
password:'',
database:''
});
pool.on('connection',function(connection){
connection.query('SET SESSION auto_increment_increment=1');
});
return function(){ //返回唯一的一个pool
return pool;
}
})();
5.1.1(5.1使用)
const _ = require("../import");//引入公用
_.router.post('/add', async function (req, res, next) {
let username = req.body.name,
userpwd = req.body.pwd,
userphone = req.body.phone;
var pool = _hun.pool();
let params = [username, _hun.utils.crypt(userpwd), userphone, _hun.utils.getTime()];
pool.getConnection(function (err, conn) {
if (err) {
res.status(400).json({ status: '-200', message: '数据库连接失败' });
return;
}
conn.query(_hun.config.sql.addUser, params, function (err, rs) {
if (err) {
if(err.message.includes('Duplicate')){
res.json({
status: '-200',
message: '注册用户出错:用户名重复'
});
return;
}else{
res.json({
status: '-200',
message: '注册用户出错:' + err.message
});
return;
}
}
res.json({
status: 200,
message: '注册成功',
result: {}
});
});
conn.release();
});
});
5.2.第二种(将链接和sql语句整合在一起)
module.exports = {
mysql: {
host: 'localhost',
user: 'root',
password: '',
database: ''
},
jwt: 'l1@tql&622ylK@9&'
sql: {
getUserInfo: 'SELECT * from user where user_id = ?',
addUser: 'INSERT INTO `user` (user_name,user_pwd,user_phone,user_time) VALUES (?, ?, ?, ?)',
userLogin: 'SELECT * from user where user_name = ? and user_pwd = ?'
}
};
5.2.1(5.2使用)
.router.post('/login', async function (req, res) {
var username = req.body.name,
userpwd = req.body.pwd;
var data = await _hun.db.query({
sql: _hun.config.sql.userLogin,
data: [username, _hun.utils.crypt(userpwd) ]
})
if (data.length != 0 ){
var token = _hun.jwt.sign({
id: data[0].user_id,
username: data[0].user_name
}, _hun.config.jwt, {
expiresIn: 60*60*24 //token(24)生效时间
});
res.json({
status: 200,
message: '登录成功',
result: {
token: token
}
});
} else {
res.json({
status: 404,
message: '账户名或密码有误',
result: null
});
}
});
6.跨域处理
放在app.js里
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Credentials", true)
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, OPTIONS')
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, token, data')
if (req.method == 'OPTIONS') {
res.sendStatus(200)
} else {
next()
}
});
7.token拦截
const config = require("../config")
const rsa = require("../utils/rsa")
const jwt = require('jsonwebtoken');
/**
* 拦截器,验证 token,data
* @type {{Validator(*, *, *): void}}
*/
module.exports = {
Validator(req, res, next) {
if(req.url == config.filter.login || req.url == config.filter.add) {
next()
} else {
if(req.headers.hasOwnProperty("authorizations")) {
jwt.verify(req.headers.authorizations,config.jwt,function(err,decode){
if(err){
res.json({
status: 500,
message: '身份凭证失效或不存在,请登录'
})
}else{
next();
}
});
} else { // 无token
res.json({
status: 500,
message: '缺少token参数,请检查',
})
}
}
}
}
可以使用网页版PostMan配合使用
包地址 git地址