前言:
此刻我们对“nginxnodejsexpress”大致比较关切,朋友们都需要学习一些“nginxnodejsexpress”的相关文章。那么小编同时在网上搜集了一些有关“nginxnodejsexpress””的相关资讯,希望同学们能喜欢,朋友们快快来学习一下吧!摘要:使用NodeJs+Express框架快速构建轻量级API服务,向用户提供数据服务。本文使用JWT模块APP认证+SSL认证,提供安全可靠的HTTPS API应用请求服务并实现后台调度。
JWT注册及生成认证流程图
NodeJs Express框架前后端交互流程图
项目结构明细分析
config: 数据库连接信息及JWT认证秘钥
controllers:用户注册信息及生成Token
middleware:检测用户信息及Token是否正确
models:Sequelize模块向后台数据库创建并写入用户信息
routes:创建注册用户信息、Token信息等APIs
server.js:主程序调度入口
本文考虑到提供轻量级API服务,没有使用原有项目架构,将执行代码统一放在server.js执行。
正式开始项目搭建:
Step1:下载Nodejs并检验
Step2: 创建项目目录下载Nodejs依赖包并检测是否下载完成
mkdir restful-apinpm init -y ##create a package.json automaticallynpm install express sequelize pg pg-hstore body-parser cors jsonwebtoken bcryptjs --save
Step3: 引入项目依赖包
const jwt = require('jsonwebtoken'); //used to create, sign, and verify tokens
const cors = require('cors');
const pgsql = require('pg');
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
var fs = require('fs');
var http = require('http');
var https = require('https');
const Sequelize = require("sequelize");
Step4: 创建HTTP/HTTPS请求
var credentials = {
key: fs.readFileSync('./private.pem'),
cert: fs.readFileSync('./file.crt')
};
var httpsServer = https.createServer(credentials,app);
var httpServer = http.createServer(app)
var PORT = 8088;
var SSLPORT = 443;
httpServer.listen(PORT, function() {
console.log('HTTP Server is running on: ;, PORT);
});
httpsServer.listen(SSLPORT, function() {
console.log('HTTPS Server is running on: ;, SSLPORT);
});
Step5: 创建Postgres数据库连接,本文使用Huawei DWS
// parse application/json
app.use(bodyParser.json());
//create database connection
const conn = new pgsql.Client({
host: 'ip',//change to your host ip
port: 8000,
user: 'dbadmin',//your db username
password: '******',//your db password
database: 'postgres',
poolSize: 5
});
conn.connect((err) =>{
if(err) throw err;
console.log('DWS Connected...');
});
app.use(cors());
// 只支持 application/x-www-form-urlencoded 文件结构
// app.use(bodyParser.urlencoded({ extended: false }))
let jsonParser = bodyParser.json();
let urlencoded = bodyParser.urlencoded({ extended: false });
Step6: Sequelize模块声明用户信息,本文提前在DWS创建table users
module.exports = (sequelize, Sequelize) => {
const user = sequelize.define("users", {
name: {
type: Sequelize.STRING
},
pass: {
type: Sequelize.STRING
}
});
return user;
};
Step7: JWT模块注册用户信息并生成客户Token,本文在用户注册及信息认证做了修改
//signup username and password to database
app.post('/signup', jsonParser, function (req, res) {
let name = req.body.name;
let pass = req.body.pass;
let sql_qurey = "insert into users values ('"+name+"' ,'"+pass+"')";
conn.query(sql_qurey, function (error, results) {
if (error) {
console.log(error)
}
res.send(JSON.stringify({"status": 200, "message": "User registered successfully!", "response": results.rows}));
})
});
//generate token
app.post('/signin',jsonParser,(req,res)=>{
let name = req.body.name;
let pass = req.body.pass;
let sql_qurey = "select * from users where name='"+name+"' and pass='"+pass+"'";
conn.query(sql_qurey, function (error, results) {
if (results.rows=='') {
res.send(JSON.stringify({"status": 404, "message": "please check the username or password!"}));
} else {
let secret = "bezkoder-secret-key"
let token = jwt.sign({ name: req.body.name }, secret, {
expiresIn: 60*60*24*7 // 24*7 hours
});
res.status(200).send({
name: req.body.name,
accessToken: token
});
}
})
});
Step8: 检测用户Token是否有效
//每次切换都去调用此接口 用来判断token是否失效 或者过期
app.post('/checkUser',jsonParser,(req,res)=>{
let token = req.get("Authorization"); // 从Authorization中获取token
let secretOrPrivateKey="bezkoder-secret-key"; // 这是加密的key(密钥)
jwt.verify(token, secretOrPrivateKey, (err, decode)=> {
if (err) { // 时间失效的时候 || 伪造的token
res.send({'status':10010, "message": "token is invalid, please make in mind the token valid date is 24*7h!"});
} else {
res.send({'status':10000, "message": "token is valid, please make sure you have updated your token every week!"});
}
})
});
Step9: 自定义API接口,提供数据服务
//get data from database
app.get('/Inbound/:data_year', function (req, res) {
//var data_year = req.params.data_year;
console.log("######################################");
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
// decode token
if (token) {
// verifies secret and checks exp
let secret = "bezkoder-secret-key"
jwt.verify(token, secret, function(err, decoded) {
console.log(err);
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
//sql
let sql_qurey = "select * from tables";//change to your SQL query
//query(sql,callback)
if(req.protocol === 'https') {
conn.query(sql_qurey, function (error, results) {
if (error) {
console.log(error)
}
//res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
res.send(JSON.stringify(results.rows));
//conn.end();
//conn.end();
})
}
else {
conn.query(sql_qurey, function (error, results) {
if (error) {
console.log(error)
}
//res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
res.send(JSON.stringify(results.rows));
//conn.end();
//conn.end();
})
}
}
});
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
Step10: 启动项目代码,Postman检测API服务,是否可以成功获取数据
启动index.js
Postman注册用户登录信息及后台用户检测
Postman生成Token
Postman发送HTTPS/HTTP请求获取数据
Step11: 后台启动
let Service = require('node-windows').Service;
let svc = new Service({
name: 'RestfulAPI', //服务名称
description: 'RestfulAPI for sharing data', //描述
script: 'C:/nodejs/restful-api/' //nodejs项目要启动的文件路径
});
svc.on('install', () => {
svc.start();
});
svc.install();
标签: #nginxnodejsexpress