首先,可以通过npm或者淘宝镜像cnpm全局安装epress框架,这里不具体说了
npm install -g express
npm install -g express-generator
新建一个项目
express -e xxx
目录说明:
bin:项目的启动文件,也可以放其他脚本。
node_modules:用来存放项目的依赖库。
public:用来存放静态文件(css,js,img)。
routes:路由控制器。
views:视图目录(相当于MVC中的V)。
app.js:项目入口及程序启动文件。
package.json:包描述文件及开发者信息。
-----------------------------------------------其他,自己创建使用------------------------------
actions:控制器,对请求的操作(相当于MVC中的C)。
plugs:数据库操作、邮件帮助等文件。
config:配置目录。
Dockerfile:做自动化部署的配置文件。
.gitignore:上传git的忽略文件配置。
README.md:项目说明文件。
app.js文件:
1 /** 2 * 应用程序的入口文件 3 */ 4 //加载express模块 5 const express = require('express'); 6 const bodyParser = require('body-parser'); 7 const http = require('http'); 8 const path = require('path'); 9 const cookieParser = require('cookie-parser'); 10 const api = require('./routes/api'); 11 const logConfig = require('./logs/logconfig/logconfig'); 12 const requestLogger = logConfig.getLogger();//根据需要获取logger 13 const loginFlag = require('./routes/checklogin'); 14 const app = express(); 15 //设置跨域访问 16 app.all('*', function (req, res, next) { 17 if(req.headers.origin) { 18 res.header("Access-Control-Allow-Origin", `${req.headers.origin}`); 19 } else { 20 res.header("Access-Control-Allow-Origin", `*`); 21 } 22 res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS'); 23 res.header("Access-Control-Allow-Credentials", "true"); 24 res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,x-access-token, x-access-site"); 25 res.header("Access-Control-Expose-Headers", "*"); 26 if(req.method === "OPTIONS") { 27 return res.end(); 28 } 29 next(); 30 }); 31 // view engine setup 32 app.set('views', path.join(__dirname, 'views')); 33 app.set('view engine', 'jade'); 34 logConfig.useLogger(app, requestLogger); 35 app.use(express.json({limit: '50mb'})); 36 app.use(express.urlencoded({ limit: '50mb',extended: true })); 37 app.use(cookieParser()); 38 app.use(express.static(path.join(__dirname, 'public'))); 39 40 //MARK: 健康检查 41 app.get('/healthz', (req, res) => { 42 res.status(200).send({ 43 error: false, 44 result: 'healthz working' 45 }) 46 }); 47 48 // //先检查是否登录 49 app.use('/api', (req, res, next) => { 50 loginFlag.authentication(req, res, next); 51 }) 52 53 app.use('/api', api); 54 55 // catch 404 and forward to error handler 56 app.use(function (req, res, next) { 57 var err = new Error('Not Found'); 58 err.status = 404; 59 next(err); 60 }); 61 62 // error handler 63 app.use(function (err, req, res, next) { 64 // set locals, only providing error in development 65 res.locals.message = err.message; 66 res.locals.error = req.app.get('env') === 'development' ? err : {}; 67 68 // render the error page 69 res.status(err.status || 500); 70 res.send('error'); 71 }); 72 module.exports = app;
routes部分重要代码:
1 const express = require('express'); 2 const router = express.Router(); 3 const Home=require('../action/home/home'); 4 5 router.get('/v2/home/getactions',Home.GetActions); 6 router.post('/v2/home/deleteaction',Home.DeleteAction); 7 router.post('/v2/home/operationactions',Home.OperationActions); 8 9 module.exports = router;
actions部分重要代码:
1 const pSqlClientExecute = require('../../plugs/postgresqldb'); 2 const Util = require('../../utils/utils'); 3 const fs = require("fs"); 4 const util = require("util"); 5 const ejsexcel = require('../../download/ejsexcel'); 6 const readFileAsync = util.promisify(fs.readFile); 7 const writeFileAsync = util.promisify(fs.writeFile); 8 const Home = {}; 9 10 Home.GetBIChartsData = (req, res, next) => { 11 console.log('fatppis call api {/v2/home/getbichartsdata}') 12 let { DateTime,Shift_ID, Area,CustomerFamily_ID,OrderBy} = req.query; 13 if(CustomerFamily_ID==null||CustomerFamily_ID==undefined){ 14 CustomerFamily_ID=''; 15 } 16 let databaseFn = async function() { 17 let sqlList = `SELECT * FROM "sp_FOP_GetBIChartsData"('${DateTime}',${Shift_ID},'${Area}','${CustomerFamily_ID}','${OrderBy}')`; 18 let sqlListFn = await pSqlClientExecute(req,sqlList, []); 19 return sqlListFn; 20 } 21 databaseFn().then((data) => { 22 res.send({ 23 status: 200, 24 data: data 25 }); 26 }) 27 .catch((error) => { 28 res.status(400).json({ 29 msg: error.detail||error.message 30 }) 31 }); 32 }
package.json文件
1 { 2 "name": "server", 3 "version": "1.0.0", 4 "description": "", 5 "main": "app.js", 6 "scripts": { 7 "start": "node ./bin/www" 8 }, 9 "author": "", 10 "license": "ISC", 11 "dependencies": { 12 "body-parser": "^1.18.2", 13 "cookie-parser": "~1.4.3", 14 "cookies": "^0.7.1", 15 "express": "^4.16.3", 16 "express-session": "^1.15.6", 17 "node-rest-client": "^3.1.0", 18 "path": "^0.12.7", 19 "pg": "^7.4.1", 20 "log4js": "^3.0.6" 21 } 22 }
项目源码链接:https://github.com/ZhijianPu/nodejsapidemo.git
来源:https://www.cnblogs.com/pzj1023/p/11743789.html