微信小程序,腾讯云node环境后台koa2开发框架(本地调试、接口、静态文件服务、文件长传服务)

原创
2018/01/18 19:56
阅读数 2.7K

项目参考地址:https://gitee.com/hkgit/nodeServerDemo

小程序node服务用chrome浏览器调试(Node.js 6.3+,Chrome 55+)

修改package.json代码如下:

执行npm run dev,打开微信web开发者工具或者chrome浏览器,打开调试即可看到

入口app.js(app.js)

const Koa = require('koa')
const app = new Koa()
const path = require('path')
const debug = require('debug')('koa-weapp')
const response = require('./middlewares/response')
const bodyParser = require('koa-bodyparser')
const config = require('./config')
const koastatic = require('koa-static')
const convert = require('koa-convert')
const staticCache = require('koa-static-cache')
const compress = require('koa-compress')
// const cors = require('koa2-cors')

// 跨域设置
// app.use(convert(cors({
//     origin: function(ctx) {
//         return '*' // 本地环境
//         // return 'https://xxxxx.qcloud.la' // 测试环境
//         // return 'https://xxxxx.xxxxx.club' // 开发环境
//     },
//     allowMethods: ['POST', 'GET', 'OPTIONS']
// })))

// 使用响应处理中间件
app.use(response)

// 解析请求体
app.use(bodyParser())

// 中间件 设置gzip
app.use(compress({
    threshold: 2048,
    flush: require("zlib").Z_SYNC_FLUSH
}))

// 静态文件服务
app.use(convert(staticCache(path.join(__dirname, 'public'), {
    maxAge: 365 * 24 * 60 * 60,
    dynamic: true
})))

// 引入路由分发
const router = require('./routes')
app.use(router.routes())

// 启动程序,监听端口
app.listen(config.port, () => debug(`listening on port ${config.port}`))

数据库配置成本地数据库(config.js)

knex链接mysql配置(tools/mysql.js)

const configs = require('../config')

module.exports = require('knex')({
    client: 'mysql',
    connection: {
        host: configs.mysql.host,
        port: configs.mysql.port,
        user: configs.mysql.user,
        password: configs.mysql.pass,
        database: configs.mysql.db,
        charset: configs.mysql.char
    }
})

定义post接口,实现文件上传(routes/index.js)

    /**
 * ajax 服务路由集合
 */
const router = require('koa-router')({
    prefix: '/weapp'
})

const controllers = require('../controllers')
const multer = require('koa-multer')
const path = require('path')
const fs = require('fs')

global.fileNum = 0
const storage = multer.diskStorage({
    //文件保存路径
    destination: function(req, file, cb) {
        const dir = path.join(__dirname, `../public/${req.body.folder}`)
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir);
        }
        cb(null, dir)
    },
    //修改文件名称
    filename: function(req, file, cb) {
    	const filename = `${Date.now()}${Math.ceil(Math.random() * Math.random() * 111)}.${file.originalname.split(".").pop()}`
        if (req.body.folder == 'musics') {
            req.body.source = `${req.body.folder}/${filename}`
        } else if (!req.body.card) {
            req.body[file.fieldname] = `${req.body.folder}/${filename}`
        } else {
            if (!req.body['files']) {
                req.body['files'] = {}
            }
            req.body['files'][req.body.fileIndex.split(',')[global.fileNum]] = filename
            global.fileNum++
        }
        cb(null, filename)
    }
})

const upload = multer({ storage: storage })

const cardFiles = [{
    name: 'float_url', /* input的name值 */
    maxCount: 1
}, {
    name: 'display_url',
    maxCount: 1
}, {
    name: 'swiper_url',
    maxCount: 1
}, {
    name: 'share_url',
    maxCount: 1
}]

// --- 贺卡index页面数据 --- //
router.post('/index_data', controllers.index_data)

// --- 贺卡kind页面数据 --- //
router.post('/kind_data', controllers.kind_data)

// --- 贺卡card页面数据 --- //
router.post('/card_data', controllers.card_data)

// --- 登录接口 --- //
router.post('/login', controllers.login)

// --- 贺卡管理接口,多文件上传,不同的name --- //
router.post('/card', upload.fields(cardFiles), controllers.card)

// --- 修改密码接口 --- //
router.post('/resetPass', controllers.resetPass)

// --- 修改密码接口 --- //
router.post('/kind', controllers.kind)

// --- 修改祝福语接口 --- //
router.post('/wish', controllers.wish)

// --- 修改音乐接口,单文件上传,source为input的name值 --- //
router.post('/music', upload.single('source'), controllers.music)

// --- 修改图片接口,多个同name文件上传 --- //
router.post('/image', upload.array('source', 50), controllers.image)

module.exports = router

实现接口,操作数据库(controllers/index_data.js)

const DB = require('../tools/mysql')

module.exports = async ctx => {
  ctx.body = await DB('card')
    .join('style', 'card.style', '=', 'style.id')
    .select('card.id', 'card.title', 'style.code as style', 'card.recommend', 'card.swiper', 'card.display_url', 'card.swiper_url')
    .where('card.show', 1)
    .orWhere('card.swiper', 1)
    .orWhere('card.recommend', 1)
}

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
2 收藏
0
分享
返回顶部
顶部