终于写到查数据这步了,后面都是筹备工作。
查问页面page.html:

//page.html<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Document</title></head><body>    <input type="text" id="tablename" placeholder="请输出表名">    <button id="bt">提交</button>    <h4 id="test"></h4>    <script src="page.js"></script></body></html>

查问的page.js:

//page.jsvar test = document.getElementById('test');var bt = document.getElementById('bt');bt.onclick = function () {    var stname = document.getElementById('tablename').value;    //生成JSON字符串    var value = "{\"tablename\" : \"" + stname + "\"}";    var xmlHttp = new XMLHttpRequest();    xmlHttp.onreadystatechange=function()    {        if (xmlHttp.readyState==4 && xmlHttp.status==200)        {            test.innerHTML = xmlHttp.responseText;            var o = JSON.parse(xmlHttp.responseText);            var sdata = (o.data)[0].toString(); //data是数组,因为会返回多条记录            var odata = JSON.parse(sdata);            console.log(odata.distname);        }    };    xmlHttp.open('POST', 'http://127.0.0.1:6060/', true);     xmlHttp.setRequestHeader("Content-type","application/json;charset=UTF-8");    xmlHttp.send(value);      //对象转json};


输出要查问的表名并提交。

node.js代码:

// query.jsconst http = require('http');const request = require('request');var urltool = require('url');  var fs = require('fs'); //引入 fs 模块var accessTokenJson = require('./wechat/access_token');//引入本地存储的 access_tokenconst hostIp = '127.0.0.1';const apiPort = 6060;const data={    appid:"wx4$%#%#%#",//你的微信小程序的appid    secret:"@##¥¥……¥##R¥",//你的微信小程序的appsecret    grant_type:"client_credential",    env:"^%$#^@^" //你的微信小程序的环境参数};var express = require('express');var app = express();var bodyParser = require('body-parser');app.use(bodyParser.json()); // for parsing application/json//allow custom header and CORSapp.all('*',function (req, res, next) {  res.header('Access-Control-Allow-Origin', '*');  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');   if (req.method == 'OPTIONS') {    res.sendStatus(200); /让options申请疾速返回/  }  else {    next();  }});app.post('/', function (req, res) {  getAccessToken(res);  //解决微信小程序后盾查问函数  getCollectionFeedback(res,req);}) function getAccessToken(res){  //获取以后工夫   var currentTime = new Date().getTime();  const url='https://api.weixin.qq.com/cgi-bin/token?appid='+data.appid+'&secret='+data.secret+'&grant_type='+data.grant_type;  if(accessTokenJson.access_token === "" || accessTokenJson.expires_time < currentTime){    request({      url: url,//申请门路      method: "GET",//申请形式,默认为get      headers: {//设置申请头          "content-type": "application/json",      },      body: JSON.stringify(data)//post参数字符串  将对象转JSON    }, function(error, response, body) {      if (!error && response.statusCode === 200) {        var obj = JSON.parse(body); //将JSON字符串转为对象        accessTokenJson.access_token = obj.access_token;        accessTokenJson.expires_time = new Date().getTime() + (parseInt(obj.expires_in) - 200) * 1000;        //更新本地存储的        fs.writeFile('./wechat/access_token.json',JSON.stringify(accessTokenJson),(err)=>{console.log("write OK")});      }   });  }}function getCollectionFeedback(res,req){     //查问feedback  const dist = req.body.tablename;  //application/json传递回来的req.body是对象  const query="db.collection(\"" + dist + "\").where({}).get()";  const querydata={    env:data.env,    query:query  }  const url='https://api.weixin.qq.com/tcb/databasequery?access_token=' +  accessTokenJson.access_token;  request({    url: url,//申请门路    method: "POST",//申请形式,默认为get    headers: {//设置申请头      "content-type": "application/json",    },    body: JSON.stringify(querydata)//post参数字符串  }, function(error, response, body) {    if (!error && response.statusCode === 200) {      //编码类型      res.setHeader('Content-Type', 'text/plain;charset=UTF-8');      //返回代理内容      //console.log("返回数据:"+JSON.stringify(body));      res.end(body);    }  });}var server = app.listen(apiPort, function () {  console.log('代理接口,运行于 http://' + hostIp + ':' + apiPort + '/'); })

express的post通过req.body获取客户端XMLHttpRequest发送的值,因为咱们规定了传递格局是application/json,所以这里的body是对象,可间接用相似req.body.tablename的办法获取要查问的表名。

微信小程序的数据库查问接口返回的是json数据格式:

对于微信小程序数据库拜访参见云开发 HTTP API 文档