前言:
這次使用node express jwt實現一個小小的認證,資料庫之類的慢慢在新增上去,先跑通整個流程,基本上是可以使用到專案裡面的了。這次就不用gulp編譯了,新增了log4.js一個錯誤日誌,還稍微做了一下壓測。就不詳細展開了,有興趣的可以下載來看:github地址
和前端對應:前端架構之vue+axios 前端實現登入攔截(路由攔截、http攔截)
大致流程:每次請求進來,都必須經過retoken.js,驗證是否帶token頭部,若有則next(),沒有則返回錯誤資訊。當然也可以設定不需要認證的介面,判斷後直接next()。
1.目錄結構:
開始吧,config:配置檔案,controllers:控制路由,logs:錯誤日誌,middleware:一些中介軟體,model:資料互動,router:路由分發
2.編寫app.js
app.js
import express from 'express';
import bodyParser from 'body-parser'
import cookieParser from 'cookie-parser'
import session from 'express-session'
import log4js from 'log4js';
import CONFIG from './config';
import api from './router/api'
// import errorHandler from './middleware/logger';
let app = express();
//中介軟體設定
app.use(cookieParser('sessionCaptcha'))
app.use(session({
secret: 'sessionCaptcha', // 與cookieParser中的一致
resave: true,
saveUninitialized: true,
name: 'USER_INFO_ID'
}))
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
// 路由
app.use('/', api)
//錯誤處理
log4js.configure({
appenders: { cheese: { type: 'file', filename: './logs/chen.log' } },
categories: { default: { appenders: ['cheese'], level: 'error' } }
});
const logger = log4js.getLogger('cheese');
//只會記錄error級別以上的錯誤
logger.error('Cheese is too ripe!');
logger.fatal('Cheese was breeding ground for listeria.');
//容錯處理機制
app.use(logErrors);
app.use(clientErrorHandler);
app.use(errorHandler);
function logErrors(err, req, res, next) {
console.error('記錄日誌', err.stack);
next(err);
}
function clientErrorHandler(err, req, res, next) {
if (req.xhr) {
res.status(500).send({ error: 'Something blew up!' });
} else {
next(err);
}
}
function errorHandler(err, req, res, next) {
res.status(500);
res.send('你錯了');
}
app.use(function (req, res, next) {
if (res.status(404)) {
res.send('Sorry cant find that!404')
}else{
next()
}
})
var server = app.listen(CONFIG.get('port'), CONFIG.get('url'), () => {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});複製程式碼
config>index.js 配置資訊
const CONFIG = new Map()
//設定埠
CONFIG.set('port', 3000)
//設定url
CONFIG.set('url', '127.0.0.1')
export default CONFIG複製程式碼
3.編寫router api
api.js router分發
import {Router} from 'express'
import jwt from 'jsonwebtoken'
import retoken from './retoken'
import indexController from '../controllers'
const router = Router()
//設定跨域
router.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("Access-Control-Request-Headers:content-type,xfilecategory,xfilename,xfilesize");
res.header("X-Powered-By",' 3.2.1')
if(req.method=="OPTIONS") res.send(200);/*讓options請求快速返回*/
else next();
});
//新增token認證
router.use(retoken)
//實現登入
router.use('/login', (req, res, next) => {
console.log(111)
//設定個人資訊
const userToken = {
name: '1',
loginAt: +new Date
}
//簽發token 指定過期時間2h
const token = jwt.sign(userToken, 'chen', { expiresIn: '2h' });
res.json({
code: 200,
data: token
})
})
router.use('/index', (req, res, next) => {
res.json({
code: 200,
data: 'henhao'
})
})
//路由
router.use('/user',indexController)
export default router複製程式碼
retoken.js token認證
import jwt from "jsonwebtoken";
import api from "./unLogin";
let unLogin = api.unLogin
export default function (req, res, next) {
let method = req.method.toLowerCase()
let path = req.path
//介面不需要登陸:直接next
//判斷method型別,並且是否包含path
if(unLogin[method] && unLogin[method].indexOf(path) !== -1){
console.log('到這裡不用驗證喔')
return next()
}
const token = req.headers.authorization
// console.log(req.headers)
//沒有token值,返回401
if (!token) {
return res.json({
code: 401,
msg: 'you need login:there is no token'
})
}
//認證token
jwt.verify(token, 'chen', (err, decoded) => {
console.log('這邊需要驗證才行喔')
if(err){
return res.json({
code: 401,
msg: err.msg
})
} else {
// 將攜帶的資訊賦給req.user
req.user = decoded
return next()
}
})
}複製程式碼
unLogin.js 不需要登入認證的介面
export default {
unLogin: {
get: [
'/index',
'/user'
],
post: [
'/login'
],
put: [],
delete: [],
}
}複製程式碼
4.編寫controllers models
controllers>index.js
import express from 'express'
import indexMode from '../model'
let router = express.Router()
router
.get('/', (req, res, next) => {
indexMode.getData(function (data) {
res.json(data)
})
})
.put('/', (req, res, next) => {
res.json({
code:200,
data: 'put'
})
})
export default router複製程式碼
models>index.js
let indexModel={
//這裡運算元據庫
getData:function (cb) {
var data = {
code:200,
data:{
username:111,
password:222
}
}
cb(data)
}
}
module.exports=indexModel複製程式碼
5.需要安裝的包
使用nedemon 啟動node
"dependencies": {
"body-parser": "^1.18.3",
"cookie-parser": "^1.4.3",
"express": "^4.16.3",
"express-session": "^1.15.6",
"jsonwebtoken": "^8.3.0",
"log4js": "^3.0.2"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"nodemon": "^1.18.3"
}複製程式碼
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon app.js --exec babel-node --presets es2015,stage-2"
},複製程式碼
使用npm run dev 啟動後
訪問 http://127.0.0.1:3000/index
訪問 http://127.0.0.1:3000/user
這樣便實現了node server的jwt認證,連線資料庫那方面,等下次更新,下一步需要在前端那邊做相關的配置了。
6.使用wrk壓測一下
安裝
wrk支援大多數類UNIX系統,不支援windows。需要作業系統支援LuaJIT和OpenSSL,不過不用擔心,大多數類Unix系統都支援。安裝wrk非常簡單,只要從github上下載wrk原始碼,在專案路徑下執行make命令即可。
git clone https://github.com/wg/wrk複製程式碼
make之後,會在專案路徑下生成可執行檔案wrk,隨後就可以用其進行HTTP壓測了。
壓測
在當前目錄下輸入 ./wrk -t8 -c200 -d30s --latency 'http://127.0.0.1:3000/index'
使用8個執行緒200個連線,對http://127.0.0.1:3000/index
進行了30秒的壓測
Running 30s test @ http://127.0.0.1:3000/index
8 threads and 200 connections
Thread Stats Avg Stdev Max +/- Stdev
(平均值) (標準差) (最大值)(正負一個標準差所佔比例)
Latency 65.99ms 15.58ms 185.51ms 89.74%
(延遲)
Req/Sec 380.14 126.58 505.00 57.24%
(處理中的請求數)
Latency Distribution (延遲分佈)
50% 60.90ms
75% 62.99ms
90% 82.57ms
99% 127.67ms
90428 requests in 30.06s, 93.72MB read(30.06秒內共處理完成了90428個請求,讀取了93.72MB資料)
Socket errors: connect 0, read 145, write 0, timeout 0
Requests/sec: 3008.58 (平均每秒處理完成3008.58個請求)
Transfer/sec: 3.12MB (平均每秒讀取資料3.12MB)複製程式碼