首页 > 技术文章 > 小程序相关

pengdt 2020-06-09 10:18 原文

几个值得记录的知识点

  • 获取openId的接口
// config
module.exports = {
    xcc:{
        appid: 'appid', // 来自微信小程序后台
        AppSecret:'AppSecret', // 来自微信小程序后台
    }
}
// xcc/index.js
const config = require('../config')
const request = require('request');

function xccchat(config) {
    this.appid =  config.appid;
    this.AppSecret =  config.AppSecret;
}

// 需要加什么东西查看wx文件夹

const xcc = new xccchat(config.xcc);
module.exports = xcc;
const xcc = require("../xcc/index")
const request = require('request');

module.exports = async (ctx, next) => {
    var body = ctx.request.body; //参数
    var appid = xcc.appid;
    var secret = xcc.AppSecret;
    var url =  "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+ secret + "&js_code=" + body.code + "&grant_type=authorization_code";
    await next()
    ctx.body = await new Promise((resolve,reject) => {
        request({
            url: url,
            method: "POST",
            json: true,
            headers: {
                "content-type": "application/json",
            },
        }, function (error, response, body) {
            resolve(body)
        })
    })
}
  • 多表查询的坑,多表联合查询就是把另一个表的ObjectId作为另一个表的一个键值对,原本用微信小程序的个人openId作为ObjectId是最好的,但是mongodb不支持,所以就只能再加一个openId字段存openId的数据,多一个数据就很杂很乱
var schema = new Schema({
    _id: Schema.Types.ObjectId,  //主键 
    type: String,
    createTime:String,
    name:String,
    openId: String,
    t_user_id: {
        type: Schema.Types.ObjectId,
        ref: 'wxuser'
    },
});
  • 转发接口,小程序里需要去调用豆瓣的接口,但是豆瓣的接口既不是https,也不支持跨域访问,所以只能用自己的服务器去调用后在把拿到的数据转发给小程序
const request = require('request');

exports.get  = async (ctx, next) => {
    // post从body取值
    // get从query取值
    let body = ctx.request.body;
    var fn = new Promise((resolve,reject) => {
        // body里的url参数就是需要我们转发的接口
        request(body.url,(error, response, body) => {
            resolve(body)
        })
    })
    var fnRes = await fn
    await next()
    ctx.body = fnRes;
}
  • 转发图片,在绘制海报的时候需要先下载图片wx.downloadFile方法,但是这个也是需要后台配置https白名单的,不巧,这个图片来自外网,并且固定的IP地址,并且也不是https的,这么说还是需要自制接口去转发,我以为就是把上面的代码copy一份就可以转发图片了,结果还是错了,上面的方式拿到的是字符串的返回结果,就是图片被强转成了字符串,这段字符串再返回给前端,前端拿到的根本就不是图片文件,所以
exports.img  = async (ctx, next) => {
    // post从body取值
    // get从query取值
    let query = ctx.request.query;
    var fn = new Promise(function(resolve, reject) {
        request({
            method: 'GET',
            // 这是关键,就是设置了这个,返回值才是buffer格式
            encoding: null,
            uri: query.imgurl
        }, function (err, response, body) {
            resolve(body);
        });
    })
    var fnRes = await fn
    await next()
    ctx.status = 200;
    // 设置图片请求头
    ctx.type = 'jpg';
    ctx.set('content-disposition','attachment;filename=a.jpg')
    ctx.length = Buffer.byteLength(fnRes);
    ctx.body = fnRes;
}

推荐阅读