当前位置:网站首页>Token is used in nodejs
Token is used in nodejs
2022-07-28 01:20:00 【Yue Yan Shao Falcon】
<!--
and java equally ,token Generation / There are many ways to store , Now let's focus on one way :
That is to use :jwt ; Download dependency npm install jsonwebtoken --save
(ps: Because front end and back end separation often involves cross domain , I have already talked about . introduce cors Wait for the operation ).
For convenience I will jwt The usage of is separately encapsulated into js file
// Introducing module dependencies
var jwt = require('jsonwebtoken');
var secretOrPrivateKey="jwtSecret",// secret key , It's usually complicated , Can be stored locally on the server ; And get ;
duringTime={expiresIn:60*30};// 1 Hours expired ;
var Jwt={
setJwt:function (content) {
var token=jwt.sign(content, secretOrPrivateKey,duringTime);
return token
},
getJwt:function (token,callback) {
jwt.verify(token,secretOrPrivateKey, function(err, decode){
callback(err,decode);
});
}
};
module.exports = Jwt;
Next use :
// One : Obtain and authenticate . I'm used to app.js In the middle of token authentication
app.use(function (request,response,next) {
if(request.url=='/routers/load/doLogin'||request.url=='/routers/load/doRegist'){// Can be more . Don't list
next();
}else{
var token=request.body.token;
if(token&&token!=''){
// verification token
Jwt.getJwt(token,function (err,decode) {
if (err) {
// When time lapses || fake token
response.send({'msgCode':-1});
} else {
// Get access
next();
}
})
}else{
//token non-existent
response.send({"msgCode":-1});
}
}
});
// Two : Generate and pass
I personally like and java The back end is the same , Separate routing from logical processing , Create a new one service Folder ; This will make the route look clean , The business process is service layer
controller layer --routers route
var express=require("express");
var routers=express.Router();
var userService=require("../../services/userService");
routers.post("/doLogin",function (request,response) {
var data={
username:request.body.username,
password:request.body.password
};
userService.findUser(data,function (res) {
response.send(res)
});
});
routers.post("/doRegist",function (request,response) {
var data={
username:request.body.username,
password:request.body.password
};
userService.addUser(data,function (res) {
response.send(res)
});
});
module.exports=routers;
service layer -- Will be generated here token.
var dbName='dbUser';
var collectionName='user';
var connect=require("../myUtils/dbUtils/connet");
var sortData={};
var Jwt=require("../myUtils/jwtUtils/jwt");
var userService={
findUser:function (data,callback) {
connect.find(dbName,collectionName,data,sortData,function (res) {
if(res.length>0){
var token=Jwt.setJwt({username:data.username});
callback({
msgCode:0,
message:' Landing successful !',
token:token
});
}else{
callback({
msgCode:-1,
message:' Login failed ! Wrong user name or password '
});
}
})
},
addUser:function (data,callback) {
connect.find(dbName,collectionName,data,sortData,function (res) {
if(res.length>0){
callback({
msgCode:-1,
message:" Registration failed ! The user name is already registered "
})
}else{
var token=Jwt.setJwt({username:data.username});
connect.add(dbName,collectionName,data,function (res) {
if(res.result.n>=1){
callback({
msgCode:0,
message:" Registered successfully !",
token:token
});
}else{
callback({
msgCode:-1,
message:" Exception error , Registration failed !"
});
}
})
}
})
}
};
module.exports=userService;
Finally, what the front end needs to do is , Receive the message on the login and registration page token, Save to local (localStorage etc. ), Then you can take it with you when you get data from other pages and request data from the server
-->
See also : Yue Yan Shao Falcon
边栏推荐
- spreadsheet 导出 excel表格
- Use of postman
- Unknown database ‘xxxxx‘
- Realize ABCD letter increment
- S-RPN: Sampling-balanced region proposal network for small crop pest detection
- 激光器芯片厂商陕西源杰半导体获广发证券、中信证券等8家投资机构入股
- URDF integrated gazebo
- Safety detection risk
- 范德蒙德卷积 学习笔记
- Deepening the concept of linear algebra [23] 01 - points coordinate points and vectors vectors
猜你喜欢

安全检测风险

杂谈:一份最初就非常完善的FS跟第一版程序就要求没bug一样不切实际

Unknown database ‘xxxxx‘

Interface test practical project 02: read interface test documents and practice

Principle of logistic regression

Focal Loss讲解

The cooperation between starfish OS and metabell is just the beginning

Spool timer

C language programming | explanation and Simulation of offsetof macro

Tool function: pay the non empty field value in one workspace to the same field in another workspace
随机推荐
uni-app进阶之样式框架/生产环境
[original] [crawler series] briefly get the most popular topics, related topics and description information
如何让数字零售承接起流量时代和留量时代的发展重任,或许才是关键所在
Support Wu xiongang! Arm Chinese management sent an open letter: shocked and angry at the unwarranted allegations!
比亚迪半导体完成8亿元A+轮融资:30家知名投资机构入局,估值已达102亿元!
Un7.13: how to add, delete, modify and query in vs Code?
Redis cache penetration breakdown and avalanche
Jingfang Technology: ASML, a lithography machine manufacturer, is one of the main customers of Anterion company, which participated in the merger and acquisition of the company
Swoole定时器
Flutter 通话界面UI
Detailed explanation of swoole memory table
EWM收货ECC交货单校验逻辑问题
Insider of container network hard core technology (7) sailing on the sea depends on the helmsman
Wentai technology acquired the remaining equity of ANSYS semiconductor and obtained unconditional approval
Retinanet网络结构详解
Monitor mouse sideslip (adapt to mobile terminal)
BYD semiconductor completed the a+ round financing of 800million yuan: 30 well-known investment institutions entered the market, with a valuation of 10.2 billion yuan!
Cross desktop web container evolution
Use of swarm task task
BSP video tutorial issue 21: easy one key implementation of serial port DMA variable length transceiver, support bare metal and RTOS, including MDK and IAR, which is more convenient than stm32cubemx (