Vue local/PC access to WeChat cloud database

1. Solve the problem of cross-domain access

New file 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": "",
        },
      },
    },
  },
};

If the deployment goes online, you need to configure nginx reverse proxy, please refer to the link below
https://blog.csdn.net/weixin_41192489/article/details/118568253

2. Get 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;
      }
    },

To replace the parameters in the interface with your appid and key, you need to log in to the background of your WeChat applet, and refer to the following figure to obtain:insert image description here

3. Access WeChat cloud database

    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);
        }
      });
  }
  • Need to use the post method
  • There cannot be any in headers. "Content-Type":"application/x-www-form-urlencoded";
    You need to comment out the one in src\axios.js
// axios.defaults.headers.post["Content-Type"] =
//   "application/x-www-form-urlencoded";
  • The parameter is
          env: "你的微信云环境id",
          query: 'db.collection("user").where({No:1}).limit(10).get()',

WeChat cloud environment id In the cloud development console in the WeChat developer tool, refer to the figure below and copy the
insert image description here
content of the query with one click to the query statement of the WeChat cloud database (for syntax, refer to the development documentation of the cloud database )

  • The access_token will expire after 7200s by default, and it needs to be obtained again after expiration.

Commonly used database operation statements

Encapsulate the database operation code and create a new file 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;
  }
};

Query data

// 微信云数据库_查询
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,
    },
  });
};

Incoming query example:

  • Single condition – equal to
'db.collection("user").where({No:1}).limit(10).get()'

Query the data whose No is 1 in the user database.

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

Query the data whose account or No value is the same as value in the user database.

new data

// 微信云数据库_新增
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,
    },
  });
};

Incoming query example

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

おすすめ

転載: blog.csdn.net/weixin_41192489/article/details/130782873
おすすめ