vue 本地/PC端访问微信云数据库

1. 解决跨域访问问题

新建文件 vue.config.js

// 后端服务器地址
let url = "http://localhost:8888";
module.exports = {
    
    
  publicPath: "./", // 【必要】静态文件使用相对路径
  outputDir: "./dist", //打包后的文件夹名字及路径
  devServer: {
    
    
    // 开发环境跨域情况的代理配置
    proxy: {
    
    
      // 【必要】访问自己搭建的后端服务器
      "/api": {
    
    
        target: url,
        changOrigin: true,
        ws: true,
        secure: false,
        pathRewrite: {
    
    
          "^/api": "/",
        },
      },
      // 【范例】访问百度地图的API
      // vue文件中使用方法  this.$http.get("/baiduMapAPI/place/v2/search"
      // 最终实际访问的接口为  http://api.map.baidu.com/place/v2/search
      // 遇到以/baiduMapAPI开头的接口便使用此代理
      "/wxAPI": {
    
    
        // 实际访问的服务器地址
        target: "https://api.weixin.qq.com",
        //开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样客户端和服务端进行数据的交互就不会有跨域问题
        changOrigin: true,
        ws: true, // 是否启用websockets
        secure: false, // 使用的是http协议则设置为false,https协议则设置为true
        // 将接口中的/baiduMapAPI去掉(必要)
        pathRewrite: {
    
    
          "^/wxAPI": "",
        },
      },
    },
  },
};

若部署上线,需配置nginx反向代理,可参考下方链接
https://blog.csdn.net/weixin_41192489/article/details/118568253

2. 获取 access_token

    // 获取 access_token
    async get_access_token() {
    
    
      let res = await this.$http.get(
        "/wxAPI/cgi-bin/token?grant_type=client_credential&appid=你的appid&secret=你的app密钥"
      );
      let access_token = res.data.access_token;
      if (access_token) {
    
    
        sessionStorage.setItem("access_token", access_token);
        return access_token;
      } else {
    
    
        return false;
      }
    },

此处要将接口中的参数,更换为你的appid和密钥,需登录你的微信小程序后台,参照下图获取:在这里插入图片描述

3. 访问微信云数据库

    async login() {
    
    
      let access_token = sessionStorage.getItem("access_token");
      if (!access_token) {
    
    
        access_token = await this.get_access_token();
      }

      this.$http({
    
    
        method: "post",
        url: `/wxAPI/tcb/databasequery?access_token=${
      
      access_token}`,
        data: {
    
    
          env: "dos-6g02iqcz92dc63ff",
          query: 'db.collection("user").where({No:1}).limit(10).get()',
        },
      }).then((res) => {
    
    
        let errcode = res.data.errcode;
        // 7200s后access_token会过期,需重新执行
        if (errcode === 42001) {
    
    
          this.login();
        }

        if (errcode === 0) {
    
    
          // 获取到微信云数据库中的数据
          console.log(res.data.data);
        }
      });
  }
  • 需使用 post 方法
  • headers 中不能有 "Content-Type":"application/x-www-form-urlencoded";
    需注释掉 src\axios.js 中的
// axios.defaults.headers.post["Content-Type"] =
//   "application/x-www-form-urlencoded";
  • 参数为
          env: "你的微信云环境id",
          query: 'db.collection("user").where({No:1}).limit(10).get()',

微信云环境 id 在微信开发者工具中的云开发控制台中参照下图一键复制
在这里插入图片描述
query 的内容为微信云数据库的查询语句(语法参考云数据库的开发文档

  • access_token 默认 7200s 后会过期,过期后需重新获取。

常用数据库操作语句

对数据库操作代码进行封装,新建文件 src\utils\wxdb.js

import axios from "axios";
import "../axios.js";

// 微信云开发环境的id
const env = "你的微信云开发环境的id";

// 获取 access_token
export const get_access_token = async function () {
    
    
  let res = await axios.get(
    "/wxAPI/cgi-bin/token?grant_type=client_credential&appid=你的appid&secret=你的app密钥"
  );
  let access_token = res.data.access_token;
  if (access_token) {
    
    
    sessionStorage.setItem("access_token", access_token);
    return access_token;
  } else {
    
    
    return false;
  }
};

查询数据

// 微信云数据库_查询
export const get_data_wx = async function (query) {
    
    
  let access_token = sessionStorage.getItem("access_token");
  if (!access_token) {
    
    
    access_token = await get_access_token();
  }

  return await axios({
    
    
    method: "post",
    url: `/wxAPI/tcb/databasequery?access_token=${
      
      access_token}`,
    data: {
    
    
      env: env,
      query: query,
    },
  });
};

传入的 query 范例:

  • 单条件 – 等于
'db.collection("user").where({No:1}).limit(10).get()'

查询 user 数据库中,No为1的数据。

  • 多条件 – 或
 `db.collection("user").where(db.command.or([{account:"${
      
      value}"},{No:${
      
      value}}])).get()`

查询 user 数据库中,account 或 No 与 value 值相同的数据。

新增数据

// 微信云数据库_新增
export const add_data_wx = async function (query) {
    
    
  let access_token = sessionStorage.getItem("access_token");
  if (!access_token) {
    
    
    access_token = await get_access_token();
  }

  return await axios({
    
    
    method: "post",
    url: `/wxAPI/tcb/databaseadd?access_token=${
      
      access_token}`,
    data: {
    
    
      env: env,
      query: query,
    },
  });
};

传入的 query 范例

`db.collection("user").add({data: {account:"${
      
      this.formData.account}",password:"${
      
      this.formData.password}"}})`

猜你喜欢

转载自blog.csdn.net/weixin_41192489/article/details/130782873