终于写到查数据这步了,前面都是准备工作。
查询页面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 文档
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。