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

6次阅读

共计 3693 个字符,预计需要花费 10 分钟才能阅读完成。

终于写到查数据这步了,后面都是筹备工作。
查问页面 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.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
};


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

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 数据格式:

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

正文完
 0