当前位置:网站首页>Node sample background setup
Node sample background setup
2022-06-12 08:58:00 【Uncertain factors】
This article is mainly used for building express Frame building , There is a certain express understand , This article only logs in 、 register 、 Interface for obtaining user details , Use at the same time apidoc Generating documentation , coordination git See?
node As a back end, there are very few , Generally, it is used as a simple blog back-end or as an application layer of some large companies
1. First you must know something about node Of express The overall architecture of the framework .
Official website express
2. Install directly first
npm install -g express-generator
3. Generating project (–view It mainly uses template engine , No need to separate the front and rear platforms )
express --view=pug English name
4. Install necessary dependencies
I copied it directly here
"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. Here is the first link to the database
5.1. First package ( Direct link )
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(){
// Return the only one pool
return pool;
}
})();
5.1.1(5.1 Use )
const _ = require("../import");// Introduce public
_.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: ' Database connection failed ' });
return;
}
conn.query(_hun.config.sql.addUser, params, function (err, rs) {
if (err) {
if(err.message.includes('Duplicate')){
res.json({
status: '-200',
message: ' Error registering user : repeat of user name '
});
return;
}else{
res.json({
status: '-200',
message: ' Error registering user :' + err.message
});
return;
}
}
res.json({
status: 200,
message: ' Registered successfully ',
result: {
}
});
});
conn.release();
});
});
5.2. The second kind ( Link and sql Statements are integrated together )
module.exports = {
mysql: {
host: 'localhost',
user: 'root',
password: '',
database: ''
},
jwt: '[email protected]&[email protected]&'
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 Use )
.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) entry-into-force time
});
res.json({
status: 200,
message: ' Login successful ',
result: {
token: token
}
});
} else {
res.json({
status: 404,
message: ' Incorrect account name or password ',
result: null
});
}
});
6. Cross domain processing
Put it in app.js in
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 Intercept
const config = require("../config")
const rsa = require("../utils/rsa")
const jwt = require('jsonwebtoken');
/** * Interceptor , verification 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: ' The identity certificate is invalid or does not exist , Please log in '
})
}else{
next();
}
});
} else {
// nothing token
res.json({
status: 500,
message: ' The lack of token Parameters , Please check ',
})
}
}
}
}
You can use the web version PostMan In combination with 
Package address git Address
边栏推荐
- [character set 9] will GBK be garbled when copied to unicode?
- Domain name mapping to specified IP
- 【字符集九】gbk拷贝到Unicode会乱码?
- 第七章-更灵活定位内存地址
- Dynamic segment tree leetcode six hundred and ninety-nine
- [sklearn] lightgbm
- Chapter 3 registers (memory access)
- [advanced pointer 2] array parameter transfer & pointer parameter transfer & function pointer & function pointer array & callback function
- Background color translucent
- Chapter 7 - more flexible location of memory addresses
猜你喜欢

Background position - mixed units

The classic dog contract of smart contract (I)

ERROR 1630 (42000): FUNCTION a.avg does not exist. Check the ‘Function Name Parsing and Resolution‘

Priority issues

Analysis of 43 cases of MATLAB neural network: Chapter 7 regression of RBF Network -- Realization of nonlinear function regression

《MATLAB 神经网络43个案例分析》:第7章 RBF网络的回归--非线性函数回归的实现

《MATLAB 神經網絡43個案例分析》:第7章 RBF網絡的回歸--非線性函數回歸的實現
![[character set 8] char8_ t、char16_ t、char32_ t、wchar、char](/img/ef/e57fb345b36c84d3585fca0568b0ee.png)
[character set 8] char8_ t、char16_ t、char32_ t、wchar、char

清华大学数据挖掘笔记(一)

Flink passes in custom parameters or profiles
随机推荐
ip、DNS、域名、URL、hosts
Background attribute compound writing
《MATLAB 神经网络43个案例分析》:第7章 RBF网络的回归--非线性函数回归的实现
UMI packaging and subcontracting, and compressing to gzip
[computer use] how to change a computer disk into a mobile disk?
Handling abnormal data
Background fixing effect
API handling Android security distance
[character set 6] wide string and multi byte character conversion
[essence] explain in detail the memory management mechanism in QT
torch.logical_and()方法
Offer:[day 8 dynamic planning (simple)] --- > maximum profit of stock
sql中的Exists用法
《MATLAB 神经网络43个案例分析》:第8章 GRNN网络的预测----基于广义回归神经网络的货运量预测
Specify 404 and 500 error reporting pages.
Display the remaining valid days according to the valid period
Shell基本语法--数组
网页中加载二次元3D虚拟主播源码(1:项目介绍和源码)
Analysis of 43 cases of MATLAB neural network: Chapter 8 prediction of GRNN Network - Freight Volume Prediction Based on generalized regression neural network
Flink CheckPoint : Exceeded checkpoint tolerable failure threshold