This commit is contained in:
theluyuan 2021-09-28 11:31:17 +08:00
commit ea8b9817b1
8 changed files with 433 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
node_modules
yarn.lock

4
README.md Normal file
View File

@ -0,0 +1,4 @@
# 我的koa模板
- bin 基础依赖
- cmntroller 路由文件地址
- app.js 入口文件

72
app.js Normal file
View File

@ -0,0 +1,72 @@
var koaJwt = require('koa-jwt');
const Koa = require("koa");
const requter = require("./bin/router.js");
dbs = require("./bin/mongodb.js")('mongodb://localhost:27017',"xiangqin")
// console.log(requter)
// import requter from "./bin/router"
const app = new Koa();
app.use(koaJwt({ secret: 'gjhkhnjweuyujhgjh' }).unless({ path: [/^\/sign/,/^\/login/,/^\/images/,/^\/upload/] }));
// app.use(async (ctx, next) => {
// // 允许来自所有域名请求
// ctx.set("Access-Control-Allow-Origin", "*");
// // 这样就能只允许 http://localhost:8080 这个域名的请求了
// // ctx.set("Access-Control-Allow-Origin", "http://localhost:8080");
// // 设置所允许的HTTP请求方法
// ctx.set("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE");
// // 字段是必需的。它也是一个逗号分隔的字符串,表明服务器支持的所有头信息字段.
// ctx.set("Access-Control-Allow-Headers", "x-requested-with, accept, origin, content-type, referer, user-agent");
// // 服务器收到请求以后检查了Origin、Access-Control-Request-Method和Access-Control-Request-Headers字段以后确认允许跨源请求就可以做出回应。
// // Content-Type表示具体请求中的媒体类型信息
// ctx.set("Content-Type", "application/json;charset=utf-8");
// // 该字段可选。它的值是一个布尔值表示是否允许发送Cookie。默认情况下Cookie不包括在CORS请求之中。
// // 当设置成允许请求携带cookie时需要保证"Access-Control-Allow-Origin"是服务器有的域名,而不能是"*";
// ctx.set("Access-Control-Allow-Credentials", true);
// // 该字段可选,用来指定本次预检请求的有效期,单位为秒。
// // 当请求方法是PUT或DELETE等特殊方法或者Content-Type字段的类型是application/json时服务器会提前发送一次请求进行验证
// // 下面的的设置只本次验证的有效时间,即在该时间段内服务端可以不用进行验证
// ctx.set("Access-Control-Max-Age", 300);
// /*
// CORS请求时XMLHttpRequest对象的getResponseHeader()方法只能拿到6个基本字段
// Cache-Control、
// Content-Language、
// Content-Type、
// Expires、
// Last-Modified、
// Pragma。
// */
// // 需要获取其他字段时使用Access-Control-Expose-Headers
// // getResponseHeader('myData')可以返回我们所需的值
// //https://www.rails365.net/articles/cors-jin-jie-expose-headers-wu
// console.log(ctx.request.body)
// ctx.set("Access-Control-Expose-Headers", "myData");
// if(ctx.method == "OPTIONS"){
// ctx.body = ""
// }else{
// await next();
// }
// })
app.use(async (ctx,next)=>{
// await next();
console.log(ctx.url)
// console.time("asd")
// ctx.response.body = {a:1};
await next()
// console.log("执行")
// console.timeEnd("asd")
});
const bodyParser = require('koa-body');
app.use(bodyParser({ multipart: true }));
// console.log(requter())
app.use(requter());
app.listen(3002);
console.log("http://localhost:3002")

205
bin/mongodb.js Normal file
View File

@ -0,0 +1,205 @@
var MongoClient = require('mongodb').MongoClient;
var dburl;
let idadd = async (set) => {
let id = 0
if (set == "idadd") {
return 0;
} else {
await find('idadd', { 'set': set }).then((res) => {
if (res.data.length != 0) {
id = res.data[0].num_key
} else {
id = 1
}
})
}
if (id == 1) {
await add('idadd', { set, 'num_key': 2 })
} else if (set != "idadd") {
console.log(id)
await update('idadd', { 'set': set }, { 'num_key': id + 1 })
}
console.log(id)
return id
}
let add = async (set, data, url = dburl) => {
if (set != "idadd") {
let id = await idadd(set)
data.num_key = id
}
return new Promise((resolve, reject) => {
MongoClient.connect(url.url, { useUnifiedTopology: true, useNewUrlParser: true }, function (err, db) {
if (err) throw err;
var dbo = db.db(url.dbname);
try {
dbo.collection(set).insertOne(data, function (err, res) {
if (err) throw err;
db.close();
resolve({ code: 0 ,msg:"添加成功"});
});
} catch (error) {
reject({ code: 1, error })
}
});
})
}
let adds = async (set, data, url = dburl) => {
if (set != "idadd") {
for (let i in data) {
let id = await idadd(set)
data[i].num_key = id
}
}
return new Promise((resolve, reject) => {
MongoClient.connect(url.url, { useUnifiedTopology: true, useNewUrlParser: true }, function (err, db) {
if (err) throw err;
var dbo = db.db(url.dbname);
try {
dbo.collection(set).insertMany(data, function (err, res) {
if (err) throw err;
db.close();
resolve({ code: 0, num: res.insertedCount });
});
} catch (error) {
reject({ code: 1, error })
}
});
})
}
let remove = async (set, where, url = dburl) => {
return new Promise((resolve, reject) => {
MongoClient.connect(url.url, { useUnifiedTopology: true, useNewUrlParser: true }, function (err, db) {
if (err) throw err;
var dbo = db.db(url.dbname);
try {
dbo.collection(set).deleteOne(where, function (err, obj) {
if (err) throw err;
db.close();
resolve({ code: 0 });
});
} catch (error) {
reject({ code: 1, error })
}
});
})
}
let removes = async (set, where, url = dburl) => {
return new Promise((resolve, reject) => {
if (where == "" || Object.keys(where).length == 0) {
reject({ code: 1 })
}
MongoClient.connect(url.url, { useUnifiedTopology: true, useNewUrlParser: true }, function (err, db) {
if (err) throw err;
var dbo = db.db(url.dbname);
try {
dbo.collection(set).deleteMany(where, function (err, obj) {
if (err) throw err;
db.close();
resolve({ code: 0, num: obj.result.n });
});
} catch (error) {
reject({ code: 1, error })
}
});
})
}
let find = async (set, where = {}, page = 0, num = 0, url = dburl) => {
return new Promise((resolve, reject) => {
if (num == 0) {
MongoClient.connect(url.url, { useUnifiedTopology: true, useNewUrlParser: true }, function (err, db) {
if (err) throw err;
var dbo = db.db(url.dbname);
try {
dbo.collection(set).find(where).toArray(function (err, result) {
if (err) throw err;
resolve({ code: 0, data: result });
db.close();
});
} catch (error) {
reject({ code: 1, error })
}
});
} else {
MongoClient.connect(url.url, { useUnifiedTopology: true, useNewUrlParser: true }, function (err, db) {
if (err) throw err;
var dbo = db.db(url.dbname);
try {
dbo.collection(set).find(where).skip(num * page).limit(num).toArray(function (err, result) {
if (err) throw err;
resolve({ code: 0, data: result });
db.close();
});
} catch (error) {
reject({ code: 1, error })
}
});
}
})
}
let update = async (set, where = {}, data, defin = true, url = dburl) => {
return new Promise((resolve, reject) => {
MongoClient.connect(url.url, { useUnifiedTopology: true, useNewUrlParser: true }, function (err, db) {
if (err) throw err;
var dbo = db.db(url.dbname);
if (defin) {
data = { $set: data }
}
try {
dbo.collection(set).updateOne(where, data, function (err, res) {
if (err) throw err;
resolve({ code: 0 });
db.close();
});
} catch (error) {
reject({ code: 1, error })
}
});
})
}
let updates = async (set, where = {}, data, url = dburl) => {
return new Promise((resolve, reject) => {
MongoClient.connect(url.url, { useUnifiedTopology: true, useNewUrlParser: true }, function (err, db) {
if (err) throw err;
var dbo = db.db(url.dbname);
data = { $set: data }
try {
dbo.collection(set).updateMany(where, data, function (err, res) {
if (err) throw err;
db.close();
resolve({ code: 0, num: res.result.nModified });
});
} catch (error) {
reject({ code: 1, error })
}
});
})
}
module.exports = function (url, dbname) {
dburl = { url, dbname };
return {
add,
adds,
remove,
find,
update,
updates,
removes
}
}

47
bin/router.js Normal file
View File

@ -0,0 +1,47 @@
const fs = require("fs")
const os = require('os');
function addMapping(router, mapping) {
for (var url in mapping) {
if (url.startsWith('GET ')) {
var path = url.substring(4);
router.get(path, mapping[url]);
console.log(`register URL mapping: GET ${path}`);
} else if (url.startsWith('POST ')) {
var path = url.substring(5);
router.post(path, mapping[url]);
console.log(`register URL mapping: POST ${path}`);
} else {
console.log(`invalid URL: ${url}`);
}
}
}
function addControllers(router, controllers_dir) {
let ostype = os.type() == "Windows_NT"
let dir;
if (ostype) {
dir = __dirname.replace("\\bin", "")
} else {
dir = __dirname.replace("/bin", "")
}
var files = fs.readdirSync(dir + "/" + controllers_dir);
var js_files = files.filter((f) => {
return f.endsWith('.js');
});
for (var f of js_files) {
// console.log(`process controller: ${f}...`);
let mapping = require(dir + `/${controllers_dir}/` + f);
addMapping(router, mapping);
}
}
module.exports = function (dir) {
let
controllers_dir = dir || 'controllers', // 如果不传参数,扫描目录默认为'controllers'
router = require('koa-router')();
addControllers(router, controllers_dir);
return router.routes();
// return 1;
};

82
controllers/index.js Normal file
View File

@ -0,0 +1,82 @@
const fs = require("fs")
const path = require("path")
const jwt = require('jsonwebtoken')
function gettoken(info){
return jwt.sign(info, "gjhkhnjweuyujhgjh", { expiresIn: '2h' })
}
const index = async (ctx,next)=>{
ctx.body = "hello"
}
const sign = async (ctx,next)=>{
const {phone,pwd} = ctx.request.body
ctx.body = await dbs.add("user",{
phone,
pwd
})
}
const login = async (ctx,next)=>{
const {phone,pwd} = ctx.request.body
const res = await dbs.find("user",{phone,pwd})
if(res.data.length == 0){
ctx.body = JSON.stringify({
code:1,
data:"没有此用户或用户名密码错误"
})
}else{
const token = gettoken({phone,pwd})
ctx.body = JSON.stringify({
code:0,
data: token
})
}
}
const addlist = async (ctx,next)=>{
const {phone,name,addres,sex,birthday,money1,money2,desc,images} = ctx.request.body
ctx.body = await dbs.add("list",{phone,name,addres,sex,birthday,money1,money2,desc,images})
}
const upload = async (ctx,next)=>{
const file = ctx.request.files.file
// console.log(file)
const reader = fs.createReadStream(file.path)
// 创建写入流
// 3. 指定图片路径文件名(即上传图片存储目录)
const stream = fs.createWriteStream(path.join('images', file.name))
// 用管道将读出流 "倒给" 输入流
reader.pipe(stream)
// 4.打印上传文件在服器上存储的相对路径
console.log('uploading %s -> %s', file.name, stream.path)
// 5.重定向到基于根目录下的静态资源web访问路径展示图片
ctx.body = {
code:0,
path : stream.path
}
}
const getlist = async (ctx,next)=>{
ctx.body = await dbs.find("list")
}
const getinfo = async (ctx,next)=>{
let { num_key } = ctx.query
console.log(num_key)
num_key = parseInt(num_key)
ctx.body = await dbs.find("list",{
num_key
})
}
module.exports = {
"GET /":index,
"POST /sign": sign,
"POST /login": login,
"POST /addlist": addlist,
"POST /upload": upload,
"GET /getlist": getlist,
"GET /getinfo": getinfo,
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

21
package.json Normal file
View File

@ -0,0 +1,21 @@
{
"name": "wecat-serve-demo",
"version": "1.0.0",
"main": "index.js",
"repository": "http://git.luyuan.tk/pplokijuhyg/wecat-serve-demo.git",
"author": "pplokijuhyg <1162963624@qq.com>",
"license": "MIT",
"scripts": {
"start": "node app.js"
},
"dependencies": {
"fs": "^0.0.1-security",
"jsonwebtoken": "^8.5.1",
"koa": "^2.11.0",
"koa-body": "^4.2.0",
"koa-bodyparser": "^4.2.1",
"koa-jwt": "^4.0.3",
"koa-router": "^7.4.0",
"mongodb": "^3.3.5"
}
}