Skip to content

NodeJS

NPM

# 查看当前镜像地址
npm config get registry

# npm 原始地址
npm set registry https://registry.npmjs.org/

# npm 淘宝地址
npm config set registry https://registry.npm.taobao.org


# npm清除缓存
npm cache clean --force
1
2
3
4
5
6
7
8
9
10
11
12

Koa

Koa安装

yarn add koa // koa
yarn add nodemon // 自动重启
yarn add koa-json // json pretty
1
2
3

添加路由

yarn add koa-router // koa 路由
yarn add koa-ejs // koa 模板引擎
1
2

POST解析

yarn add koa-bodyparser
1

数据库相关

yarn add mongoose
1

隐藏密码

yarn add bcryptjs
1

默认头像

yarn add gravatar
1

JWT

yarn add jsonwebtoken
1

验证JWT

yarn add koa-passport
yarn add passport-jwt
1
2

Pm2全局安装

yarn global add pm2
1

通用模板(Koa)

// 入口文件
const Koa = require("koa");
const {router} = require('./routes/index')



// 实例化
const app = new Koa();

// 端口
const {PORT} = require('./config/prot')

// 数据库
const {mongoose} = require('./database/index')

// 路由
app.use(router.routes())



// 启动服务
app.listen(PORT, () => {
	console.log(`Server Started on ${PORT}....`);
});

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 端口
/*
 *   端口设置
 *   production = 5001  生产环境
 *   predeploy = 5002  测试环境
 *   development = 5003  本地开发环境
 */
let portList = {
	"production": 5001,
	"predeploy": 5002,
	"development": 5003,
}
console.log("ENV log", process.env.NODE_ENV, portList[process.env.NODE_ENV]);

let PORT = portList[process.env.NODE_ENV] || 5001

module.exports = {
	PORT
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 数据库配置
const mongoose = require("mongoose");

const db = require("./key").mongoURI;
mongoose.connect(db, {
	useNewUrlParser: true,
	useUnifiedTopology: true,
}).then(() => {
	console.log("MongoDB Connected");
}).catch((e) => {
	console.log("DB Error", e);
});

module.exports = {
	mongoose
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 路由
const KoaRouter = require("koa-router");
const router = new KoaRouter();

// 路由跳转 index
router.get("/", async (ctx) => {
	ctx.body = {msg: "Hello Koa interface~"};
});




module.exports = {
	router
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

计划发布List

  • NPM & yarn
  • Experss
  • KOA
  • 线上接口服务(基于Heroku部署)

基于Express搭建的API接口服务

Released under the MIT License. Thanks to WebStorm software support.