赞
踩
1.首先我们在项目中安装好以下插件:
①.express:路由
②.sequelize :连接数据库、操作SQL
③.lodash:对数据,对象操作(功能很强大,推荐使用)
④.pg(PostgreSQL数据库):(也可使用其他数据库,像:Oracle、MySQL、MongoDB等)
⑤.cross-env:用来区分环境
⑥.nodemon:保存实时刷新
⑦.pm2:Node 应用进程管理器
⑧.log4js:记录日志
npm install express sequelize lodash pg cross-env nodemon pm2 log4js --save
2.在node_modules目录下新建app.js 跟 readme.md
├── node_modules // node依赖包
├── app.js // 新建app.js
├── package.json // package.json配置文件
├── Readme.md // 新建Readme.md
3.配置 package.json文件
{ "name": "node", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "cross-env NODE_ENV=development nodemon ./app.js", "build": "cross-env NODE_ENV=production webpack ./app.js" }, "author": "", "license": "ISC", "dependencies": { "cross-env": "^7.0.3", "express": "^4.17.1", "joi": "^17.4.2", "lodash": "^4.17.21", "log4js": "^6.3.0", "nodemon": "^2.0.14", "pg": "^8.7.1", "sequelize": "^6.7.0", "webpack": "^5.59.1" }, "devDependencies": { "webpack-cli": "^4.9.1" } }
4.配置app.js
const express = require('express');
const port = process.env.port || '8080'
const app = express();
app.listen(port, () => {
console.log(`服务启动了${port}`)
})
process.on("uncaughtException", (err) => {
console.error(err.stack);
});
到这里已经完成node的启动工作,可以在控制台看到打印的“服务启动了”的日志了
5.连接数据库
在node_modules同级目录下新建config文件,在config文件里新建development.js跟production.js,由于我们在package.json中设置了npm run dev的时候 把NODE_ENV设置为“development” ,npm run build 把NODE_ENV设置为“production” ,这样的话我们就可以根据启动的命令来区分当前环境了。
├── config
│ ├── development.js // development环境的配置
│ ├── production.js // production环境的配置
├── node_modules // node依赖包
├── app.js // 新建app.js
├── package.json // package.json配置文件
├── Readme.md // 新建Readme.md
在development.js跟production.js可以用来配置不同环境下的数据,我这里主要用来配置连接不同的环境下的数据库,演示development.js
module.exports = {
dataBase: {
"host": "xxx", // 数据库的IP
"port": "xxx", // 数据库的端口
"db": "xxx", // 数据库的名称
"password": "xxx", // 数据库的连接密码
"username": "xxx", // 数据库的连接用户名
"dialect": "postgres" // 数据库的类型,本项目用的是postgres,
}
}
在app.js里面连接数据库,
const express = require('express'); const Sequelize = require('sequelize') const port = process.env.port || '8080' const NODE_ENV = process.env.NODE_ENV const env = require("./config/" + NODE_ENV + ".js") const sequelize = new Sequelize(env.dataBase) global.sequelize = sequelize // 设置为全局变量,在写接口的时候都会用到这个插件 try { sequelize.authenticate(); console.log('Connection has been established successfully') } catch (error) { console.error('Unable to connect to the database:', error); } app.listen(port, () => { console.log(`服务启动了${port}`) }) process.on("uncaughtException", (err) => { console.error(err.stack); });
再次保存的时候,如果可以在控制台打印出来“Connection has been established successfully”,,就说明数据库已经连接成功
6.封装打印日志的方法(最好用日志系统保存,方便分布式查询)
在node_modules同级目录下新建untils文件,untils文件新建Logger.js
// level表示级别 低于什么级别则不会打印在日志上,假设你设置的是level: "error"
const log4js = require('log4js');
log4js.configure({
appenders: { logger: { type: "file", filename: "logger.log" } },
categories: { default: { appenders: ["logger"], level: "info" } }
})
const logger = log4js.getLogger("logger");
// 可使用如下方法
// logger.trace("Entering cheese testing");
// logger.debug("Got cheese.");
// logger.info("Cheese is Comté.");
// logger.warn("Cheese is quite smelly.");
// logger.error("Cheese is too ripe!");
// logger.fatal("Cheese was breeding ground for listeria.");
module.exports = logger
在app.js里引入,并设置成全局
const express = require('express'); const Sequelize = require('sequelize') const Success = require('./utils/Success') const Error = require('./utils/Error') const Result = require('./utils/Result') const Logger = require('./utils/Logger') const port = process.env.port || '8089' const NODE_ENV = process.env.NODE_ENV const env = require("./config/" + NODE_ENV + ".js") const sequelize = new Sequelize(env.dataBase) global.sequelize = sequelize; global.Logger = Logger; try { sequelize.authenticate(); Logger.info('database:Connection has been established successfully') } catch (error) { Logger.error('Unable to connect to the database:', error); } const app = express(); app.listen(port, () => { console.log(`服务启动了${port}`) }) process.on("uncaughtException", (err) => { Logger.error(err.stack); });
7.node路由,我们按照Java的MVC的格式来写
在node_modules同级目录下新建router文件,service文件,model文件,分别在router,service,model文件夹新建user.js(一般根据数据库中的表来建)
├── config
│ ├── development.js // development环境的配置
│ ├── production.js
├── model
│ ├── user.js // user表
├── node_modules // node依赖包
├── router
│ ├── user.js // user路由 相当于是Java的controler
├── service
│ ├── user.js // user service主要用来处理业务逻辑
├── utils
│ ├── Logger.js // 封装打印日志的方法
├── app.js // 新建app.js
├── package.json // package.json配置文件
├── Readme.md // 新建Readme.md
然后在model/user.js
const {Sequelize} = require('sequelize') // const sequelize = require('../utils/sequelize.js') const User=sequelize.define("user", { id: { type: Sequelize.INTEGER, // 数据类型 primaryKey: true, // 主键ID autoIncrement: true, // 自增 }, userName: { type: Sequelize.STRING, field: "user_name", allowNull: false, }, exchangeId: { type: Sequelize.INTEGER, allowNull: false, field: "exchange_id", }, address: { type: Sequelize.JSON, allowNull: false, }, createdAt: { type: Sequelize.DATE, field: "created_at", allowNull: false, defaultValue: Sequelize.NOW, }, updatedAt: { type: Sequelize.DATE, field: "updated_at", allowNull: false, defaultValue: Sequelize.NOW, }, }, { tableName: "pdt_user", // 数据库的表名 freezeTableName: false, timestamps: true, createdAt: "created_at", updatedAt: "updated_at", deletedAt: false, }) module.exports=User;
service/user.js
const User= require('../model/user') class UserService { // 查找全部 static async findAll() { const rows = await Accout.findAll() return rows } // 根据id 查询某个 static async findone(id) { const accout = await Accout.findOne({ where: { id: id } }) return accout } // 新建用户 static async create(data) { const accout = await Accout.create({userName:data.userName}) return accout.id } // 更多操作请参考sequelize的官方文档 } module.exports = UserService
route/user.js
const express = require ('express') const _ =require('lodash') const User= express.Router(); const userService = require('../service/user') User.get('/findAll',async (req,res)=>{ const {id}=req.query const idCheck = _.isEmpty(id) let ret; if(idCheck){ ret=new Error('请求id 不能为空') }else{ ret= await userService.findAll(id) } res.send(ret) }) User.get('/findone',async (req,res)=>{ const {id}=req.query; const ret= await userService.findone(id) res.send(ret) }) module.exports=User
最后在app.js里引入
const express = require('express'); const Sequelize = require('sequelize') const Success = require('./utils/Success') const Error = require('./utils/Error') const Result = require('./utils/Result') const Logger = require('./utils/Logger') const port = process.env.port || '8089' const NODE_ENV = process.env.NODE_ENV const env = require("./config/" + NODE_ENV + ".js") const sequelize = new Sequelize(env.dataBase) global.sequelize = sequelize; try { sequelize.authenticate(); Logger.info('database:Connection has been established successfully') } catch (error) { Logger.error('Unable to connect to the database:', error); } const user= require('./router/user'); const app = express(); app.use('/user', user) app.listen(port, () => { console.info(`服务启动了${port}`) }) process.on("uncaughtException", (err) => { Logger.error(err.stack); });
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。