小程序入门学习13--云函数与数据库02

<button class="call" bindtap="getFile">获取文件</button>
<button class="call" bindtap="getHttp">访问HTTP服务</button>
<button class="call" bindtap="getVersion">查询MySQL版本</button>
Page({
  //获取文件url
  getFile:function(){
    console.log("getFileButton is click")
    wx.cloud.callFunction({
      name:'getFileUrl'
    }).then(console.log)
  },
  //访问Http服务
  getHttp:function(){
    concole.log("getHttpButton is click")
    wx.cloud.callFunction({
      name:"httpRequest"
    }).then(console.log)
  },
  //获取MySQL版本
  getVersion:function(){
    console.log("getVersionButton is click")
    wx.cloud.callFunction({
      name: "getVersion"
    }).then(console.log)
  }
})

1 获取文件对应云函数---getFileUrl

const cloud = require('wx-server-sdk')

cloud.init()
exports.main = async (event, context) => {
  const fileId = ['cloud://demo1-vcczm.6465-demo1-vcczm-1301277220/1149160.png']
  return await cloud.getTempFileURL({
    fileList:fileId
  })
}

2 访问Http服务对应云函数---httpRequest

const cloud = require('wx-server-sdk')
//引入got包
const got = require('got');
cloud.init()

exports.main = async (event, context) => {
  //拿到response信息
  let response = await got('https://baidu.com'); 
  //返回给小程序
  return response.body;
}

1)建立云函数后右键-->在终端中打开-->输入npm install got

11863886-239ef9e903c17c2b
在这里插入图片描述

2)bug
Uncaught (in promise) Error: errCode: -404011 cloud function execution error | errMsg: cloud.callFunction:fail requestID 558df6e2-5165-11ea-923c-525400090c2c, cloud function service error code -504002, error message Unexpected token *; at cloud.callFunction api;
如果 got版本过高,会出现这种情况 ,可以修改对应云函数下的package.json
11863886-ee147ea084533b7b.png
在这里插入图片描述

或者导入got时, 改为

npm install [email protected]

另一种方法:小程序云函数调用http或https请求外部数据

3 云函数连接数据库

1)建立云函数后右键-->在终端中打开-->输入npm install mysql2

11863886-c41ebd37d6cd91ee
在这里插入图片描述

2)bug
(1)Access denied for user 'root'@'212.64.68.233' (using password: YES)
说明密码错了
(2)Error: connect ETIMEDOUT,有可能是远程服务器3306端口没开,如果是腾讯云可以这样 配置
(3)error message Task timed out after 3 seconds
可以考虑适当增加云函数超时时间
11863886-7a6f132f7b22435f
在这里插入图片描述

const cloud = require('wx-server-sdk')
//引入mysql操作模块
const mysql = require('mysql2/promise')
cloud.init()
// 云函数入口函数
exports.main = async (event, context) => {
  //链接mysql数据库的example_nodejs(随意)
  try {
    const connection = await mysql.createConnection({
      host: '服务器公网IP',
      user: '数据库账号',
      password: '数据库密码',
      database: 'example_nodejs'
    })
    //查询数据库版本
    const [rows, fields] = await connection.execute('SELECT version();')
    return rows;
  } catch (err) {
    console.log("链接错误", err)
    return err
  }
}

结果:


11863886-8cd9d21d36a4e863.png
在这里插入图片描述

无法输入中文

可以重启开发工具或切换输入法,个人感觉win10自带的输入法一般不会出现这种情况。

安装npm后 云函数文件夹删除失败

1)打开云开发控制台,删除对应云函数
2)关闭开发工具->找到小程序对应文件夹->删除硬盘内的云函数文件夹,再打开 开发工具就行了
领取限量云产品优惠

发布了114 篇原创文章 · 获赞 32 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/moqianmoqian/article/details/104552187