后端 nodejs
将前端发送的请求在后端进行处理(好处就是不涉及跨域问题
思路:
- 1、获取集合数据前 需要 获取集合数据总量 ,total。
- 2、获取集合数据总量的方法在微信小程序文档中为 获取特定云环境下集合信息(databaseCollectionGet) ,该api请求地址为
POST https:
- 3、获取集合数据的方法为 数据库查询记录(databaseQuery),请求地址为
POST https:
- 4、两个api都需要access_token(获取小程序全局唯一后台接口调用凭据),该凭证有效期仅为7200秒,为避免重复获取导致失效等其它问题,需要将该token保存在后端某txt文件中。请求地址为
GET https:
- ps:除了请求地址,所需参数在微信小程序文档中有详细地介绍,真实参数的请求格式我会发布出来以便大家参考,在此不加赘述。
实现:源码
const request = require("request");
const fs = require("fs");
const path = require("path");
- 获取accessToken思路:获取-保存-读取时判断是否需要再次获取(7200秒有效期)
const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=${data.grant_type}&appid=${data.appid}&secret=${data.appsecret}`;
const filePath = path.join(
__dirname,
"public",
"accessToken",
"/token.txt"
);
const readAccessToken = () => {
try {
const data = fs.readFileSync(filePath);
accessToken = JSON.parse(data);
if (accessToken.expires_in > Date.parse(new Date())) {
return Promise.resolve(accessToken.access_token);
} else {
return updateAccessToken();
}
} catch (err) {
return updateAccessToken();
}
};
const updateAccessToken = () => {
return new Promise((resolve, reject) => {
request(url, (err, response, body) => {
let accessToken = JSON.parse(response.body);
accessToken["expires_in"] = Date.parse(new Date()) + 7200 * 1000;
fs.writeFileSync(filePath, JSON.stringify(accessToken));
resolve(accessToken.access_token);
});
});
};
- 接收来自前端的命令,判断传递的参数为获取total还是data进行操作
module.exports = async (req, res) => {
const data = req.body.params;
const size = data.pagesize;
const num = data.pagenum;
const only = data.query;
const key = await readAccessToken().then((res) => {
return res;
});
if (data === "info") {
const urlInfo = `https://api.weixin.qq.com/tcb/databasecollectionget?access_token=${key}`;
const infoData = {
env: "云开发环境ID",
limit: 5,
offset: 0,
};
request(
{
url: urlInfo,
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(infoData),
},
(error, response, body) => {
const { collections } = JSON.parse(body);
res.send(collections[2]);
}
);
} else {
const urlData = `https://api.weixin.qq.com/tcb/databasequery?access_token=${key}`;
const querydata = {
env: "云开发环境ID",
query: `db.collection("集合名").where({detail:${only}}).limit(${size}).skip(${
(num - 1) * size
}).get()`,
};
const queryAlldata = {
env: "云开发环境ID",
query: `db.collection("集合名").where({}).limit(${size}).skip(${
(num - 1) * size
}).get()`,
};
if (only) {
console.log("only");
request(
{
url: urlData,
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(querydata),
},
(error, response, body) => {
const { data } = JSON.parse(body);
const newData = [];
for (let i = 0, j = data.length; i < j; i++) {
newData.push(JSON.parse(data[i]));
}
res.send(newData);
}
);
} else {
request(
{
url: urlData,
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(queryAlldata),
},
(error, response, body) => {
const { data } = JSON.parse(body);
const newData = [];
for (let i = 0, j = data.length; i < j; i++) {
newData.push(JSON.parse(data[i]));
}
res.send(newData);
}
);
}
}
}