鱼C论坛

 找回密码
 立即注册
查看: 209|回复: 1

微信小程序报错

[复制链接]
发表于 2023-12-19 16:55:41 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
我制作了一个微信小程序,有一个功能是添加菜系,能添加菜系名称和图片,并且与部分函数用的是云函数,
这是addCuisine.js的代码
  1. // Adminpackage/addCuisine/addCuisine.js
  2. const app = getApp()
  3. const db = wx.cloud.database()
  4. Page({

  5.         /**
  6.          * 页面的初始数据
  7.          */
  8.         data: {
  9.                 cuisineName: '',
  10.                 cuisineImg: [],
  11.                 cuisineImgID: [],
  12.                 isCoverImg: true,
  13.         },

  14.         /**
  15.          * 生命周期函数--监听页面加载
  16.          */
  17.         onLoad: function (options) {},


  18.         /**
  19.          * 生命周期函数--监听页面显示
  20.          */
  21.         onShow: function () {},

  22.         /**
  23.          * 获取输入框数据
  24.          */
  25.         inputData(e) {
  26.                 let value = e.detail.value
  27.                 this.setData({
  28.                         cuisineName: value
  29.                 })
  30.         },

  31.         /**
  32.          * 选择图片
  33.          */
  34.         CoverImg() {
  35.                 wx.chooseImage({
  36.                         count: 1, //张数
  37.                         sizeType: ['compressed'], //压缩图
  38.                         sourceType: ['album'], //从相册选择
  39.                         success: res => { //chooseImage-success方法,返回类型是数组
  40.                                 this.setData({
  41.                                         cuisineImg: res.tempFilePaths,
  42.                                         isCoverImg: false
  43.                                 })
  44.                         },
  45.                         fail: err => {
  46.                                 console.log('获取图片失败', err)
  47.                                 wx.showToast({
  48.                                         title: '网络错误!获取图片失败',
  49.                                         icon: 'none',
  50.                                         duration: 1000
  51.                                 })
  52.                         }
  53.                 });
  54.         },

  55.         /**
  56.          * 大图预览
  57.          */
  58.         PWCoverImg(e) {
  59.                 wx.previewImage({ //大图预览,需要的类型是数组
  60.                         urls: this.data.cuisineImg,
  61.                         current: e.currentTarget.dataset.url
  62.                 });
  63.         },

  64.         /**
  65.          * 删除图片
  66.          */
  67.         DECoverImg(e) {
  68.                 this.data.cuisineImg.splice(e.currentTarget.dataset.index, 1);
  69.                 this.setData({
  70.                         isCoverImg: true,
  71.                         cuisineImg: this.data.cuisineImg
  72.                 })
  73.         },

  74.         //取消按钮
  75.         closeInput() {
  76.                 wx.navigateBack({
  77.                         delta: 1,
  78.                 })
  79.         },

  80.         /**
  81.          * 确认提交按钮
  82.          */
  83.         confirmSubmit(e) {
  84.     wx.cloud.callFunction({
  85.       name:"adminPackage",
  86.       data:{
  87.         type:'addCuisine',
  88.         cuisineImg:this.data.cuisineImg,
  89.         name:this.data.cuisineName,
  90.       }
  91.     })
  92.       .then((resp) => {
  93.         if(resp.result){
  94.           if(resp.result.error){
  95.             wx.showToast({
  96.               title: resp.result.message || 'Unknown error',
  97.               icon:'none',
  98.               duration: 2000
  99.             });
  100.         }else{
  101.           console.log(resp.result.success);
  102.         }
  103.       } else{
  104.         wx.showToast({
  105.           title: 'Invalid response from server',
  106.           icon: 'none',
  107.           duration: 2000
  108.         });
  109.       }
  110.     })
  111.       .catch((e) =>{
  112.         console.log(e);
  113.         wx.showToast({
  114.           title:'请求失败',
  115.           icon: 'none',
  116.           duration: 2000
  117.         });
  118.       });
  119.   }
  120. })
复制代码

这是云函数的代码
  1. // 云函数入口文件
  2. const cloud = require('wx-server-sdk')

  3. cloud.init()
  4. const db = cloud.database();


  5. exports.main = async (event, context) => {
  6.   try{
  7.     const cuisineImg = event.cuisineImg
  8.     const name = event.cuisineName
  9.    
  10.                 if (name === "") {
  11.       console.log("Error:请填写菜系名称!")
  12.       return {error: true, message:'请填写菜系名称!'};
  13.                 } else if (cuisineImg.length == 0) {
  14.       console.log("请上传图标图片!")
  15.                         return {error: true, message:'请上传图标图片!'};
  16.                 } else {
  17.                         return await addImg(cuisineImg, name);
  18.     }
  19.   } catch(error){
  20.     console.error("Error in main function:", error);
  21.     return { error: true, message:'Unexpected error in cloud function!'}
  22.   }
  23.    
  24. /**
  25.          * 上传图片
  26.          */
  27.         async function addImg() {
  28.                 wx.showLoading({
  29.                         title: '上传中...',
  30.                         mask: true,
  31.                 })
  32.                 let cuisineImgFileID = []
  33.                 for (let i = 0; i < this.data.cuisineImg.length; i++) {
  34.                         let fileName = this.data.cuisineImg[i];
  35.                         let cloudPath = "SysCuisineImg/" + Date.now() + Math.floor(Math.random(0, 1) * 10000000) + '.jpg';
  36.                         await wx.cloud.uploadFile({
  37.                                         cloudPath,
  38.                                         filePath: fileName,
  39.                                 })
  40.                                 .then(res => {
  41.                                         wx.hideLoading()
  42.                                         console.log('上传图片成功:', res)
  43.                                         cuisineImgFileID.push(res.fileID)
  44.                                         if (cuisineImgFileID.length == this.data.cuisineImg.length) {
  45.                                                 this.setData({
  46.                                                         cuisineImgID: cuisineImgFileID,
  47.                                                 })
  48.                                                 this.addData()
  49.                                         }
  50.                                 })
  51.                                 .catch(err => {
  52.                                         wx.hideLoading()
  53.                                         console.log('上传图片失败:', err)
  54.                                         wx.showToast({
  55.                                                 title: '上传图片失败!',
  56.                                                 icon: 'none',
  57.                                                 duration: 1000,
  58.                                         })
  59.                                 })
  60.     }
  61.   };
  62.    
  63. /**
  64.          * 添加数据
  65.          */
  66.         async function addData() {
  67.                 wx.showLoading({
  68.                         title: '添加中...',
  69.                         mask: true,
  70.                 })
  71.                 await db.collection('SysCuisine').add({
  72.                                 data: {
  73.                                         cuisineImg: this.data.cuisineImgID,
  74.                                         cuisineName: this.data.cuisineName,
  75.                                 },
  76.                                 success: res => {
  77.                                         wx.hideLoading()
  78.                                         if (res.errMsg == "collection.add:ok") {
  79.                                                 console.log('添加成功:', res.errMsg)
  80.                                                 wx.navigateBack({
  81.                                                         delta: 1,
  82.                                                 })
  83.                                         }
  84.                                 },
  85.                                 fail: err => {
  86.                                         wx.hideLoading()
  87.                                         console.log('添加失败:', err)
  88.                                         let img = this.data.cuisineImgID
  89.                                         console.log('添加失败,要删除的图片:', img)
  90.                                         wx.cloud.deleteFile({
  91.                                                 fileList: img, //deleteFile的fileList是数组才能删除
  92.                                                 success: res => {
  93.                                                         if (res.errMsg == "cloud.deleteFile:ok") {
  94.                                                                 wx.showToast({
  95.                                                                         title: '添加失败!',
  96.                                                                         icon: 'none',
  97.                                                                         duration: 1000,
  98.                                                                 })
  99.                                                         }
  100.                                                 },
  101.                                                 fail: err => {
  102.                                                         wx.showToast({
  103.                                                                 title: '添加失败!',
  104.                                                                 icon: 'none',
  105.                                                                 duration: 1000,
  106.                                                         })
  107.                                                 }
  108.                                         })
  109.                                 }
  110.                         })
  111.         }
  112. }
复制代码

现在碰到的问题是当我按下确认按钮时并不能上传菜系,toast返回Invalid response from server,能帮我看看问题出在哪吗
@FishC
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-12-19 16:56:08 | 显示全部楼层
看代码应该是云函数返回的结果不符合预期引起的。根据你提供的代码,似乎云函数在上传图片和添加数据时,都使用了this关键字来访问data中的数据。然而,云函数中没有上下文对象,也就是没有this关键字。

因此,你需要对addImg和addData两个函数进行修改,将this.data.cuisineImg和this.data.cuisineName改为传入的参数cuisineImg和name即可。

具体来说,修改addImg如下:
  1. async function addImg(cuisineImg, name) {
  2.     // ...
  3. }
复制代码

修改addData如下:
  1. async function addData(cuisineImgID, cuisineName) {
  2.     // ...
  3. }
复制代码

然后,将addImg和addData两个函数中对应的地方使用参数来替换:

addImg函数中的数据
  1. await wx.cloud.uploadFile({
  2.     cloudPath,
  3.     filePath: fileName,
  4. }).then(res => {
  5.     // ...
  6. })
复制代码

修改为
  1. await wx.cloud.uploadFile({
  2.     cloudPath,
  3.     filePath: fileName,
  4. }).then(res => {
  5.     // ...
  6. })
复制代码

addData函数中的数据
  1. await db.collection('SysCuisine').add({
  2.     data: {
  3.         cuisineImg: this.data.cuisineImgID,
  4.         cuisineName: this.data.cuisineName,
  5.     },
  6.     success: res => {
  7.         // ...
  8.     },
  9.     fail: err => {
  10.         // ...
  11.     }
  12. })
复制代码

修改为
  1. await db.collection('SysCuisine').add({
  2.     data: {
  3.         cuisineImg: cuisineImgID,
  4.         cuisineName: cuisineName,
  5.     },
  6.     success: res => {
  7.         // ...
  8.     },
  9.     fail: err => {
  10.         // ...
  11.     }
  12. })
复制代码

修改完成后,再次测试看是否能够上传菜系。这样应该就能解决问题了。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-27 17:43

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表