node.js与微信小程序后台数据库的交互(5)给定表名查询数据

终于写到查数据这步了,前面都是准备工作。
查询页面page.html:

//page.html




    
    Document


    
    
    

查询的page.js:

//page.js
var 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
};

image.png
输入要查询的表名并提交。

node.js代码:

// query.js
const http = require('http');
const request = require('request');
var urltool = require('url');  
var fs = require('fs'); //引入 fs 模块

var accessTokenJson = require('./wechat/access_token');//引入本地存储的 access_token

const 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 CORS
app.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数据格式:
image.png

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

你可能感兴趣的:(node.js)