ZUKE824 发表于 2023-12-19 16:55:41

微信小程序报错

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

        /**
       * 页面的初始数据
       */
        data: {
                cuisineName: '',
                cuisineImg: [],
                cuisineImgID: [],
                isCoverImg: true,
        },

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


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

        /**
       * 获取输入框数据
       */
        inputData(e) {
                let value = e.detail.value
                this.setData({
                        cuisineName: value
                })
        },

        /**
       * 选择图片
       */
        CoverImg() {
                wx.chooseImage({
                        count: 1, //张数
                        sizeType: ['compressed'], //压缩图
                        sourceType: ['album'], //从相册选择
                        success: res => { //chooseImage-success方法,返回类型是数组
                                this.setData({
                                        cuisineImg: res.tempFilePaths,
                                        isCoverImg: false
                                })
                        },
                        fail: err => {
                                console.log('获取图片失败', err)
                                wx.showToast({
                                        title: '网络错误!获取图片失败',
                                        icon: 'none',
                                        duration: 1000
                                })
                        }
                });
        },

        /**
       * 大图预览
       */
        PWCoverImg(e) {
                wx.previewImage({ //大图预览,需要的类型是数组
                        urls: this.data.cuisineImg,
                        current: e.currentTarget.dataset.url
                });
        },

        /**
       * 删除图片
       */
        DECoverImg(e) {
                this.data.cuisineImg.splice(e.currentTarget.dataset.index, 1);
                this.setData({
                        isCoverImg: true,
                        cuisineImg: this.data.cuisineImg
                })
        },

        //取消按钮
        closeInput() {
                wx.navigateBack({
                        delta: 1,
                })
        },

        /**
       * 确认提交按钮
       */
        confirmSubmit(e) {
    wx.cloud.callFunction({
      name:"adminPackage",
      data:{
      type:'addCuisine',
      cuisineImg:this.data.cuisineImg,
      name:this.data.cuisineName,
      }
    })
      .then((resp) => {
      if(resp.result){
          if(resp.result.error){
            wx.showToast({
            title: resp.result.message || 'Unknown error',
            icon:'none',
            duration: 2000
            });
      }else{
          console.log(resp.result.success);
      }
      } else{
      wx.showToast({
          title: 'Invalid response from server',
          icon: 'none',
          duration: 2000
      });
      }
    })
      .catch((e) =>{
      console.log(e);
      wx.showToast({
          title:'请求失败',
          icon: 'none',
          duration: 2000
      });
      });
}
})
这是云函数的代码
// 云函数入口文件
const cloud = require('wx-server-sdk')

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


exports.main = async (event, context) => {
try{
    const cuisineImg = event.cuisineImg
    const name = event.cuisineName
   
                if (name === "") {
      console.log("Error:请填写菜系名称!")
      return {error: true, message:'请填写菜系名称!'};
                } else if (cuisineImg.length == 0) {
      console.log("请上传图标图片!")
                        return {error: true, message:'请上传图标图片!'};
                } else {
                        return await addImg(cuisineImg, name);
    }
} catch(error){
    console.error("Error in main function:", error);
    return { error: true, message:'Unexpected error in cloud function!'}
}
   
/**
       * 上传图片
       */
        async function addImg() {
                wx.showLoading({
                        title: '上传中...',
                        mask: true,
                })
                let cuisineImgFileID = []
                for (let i = 0; i < this.data.cuisineImg.length; i++) {
                        let fileName = this.data.cuisineImg;
                        let cloudPath = "SysCuisineImg/" + Date.now() + Math.floor(Math.random(0, 1) * 10000000) + '.jpg';
                        await wx.cloud.uploadFile({
                                        cloudPath,
                                        filePath: fileName,
                                })
                                .then(res => {
                                        wx.hideLoading()
                                        console.log('上传图片成功:', res)
                                        cuisineImgFileID.push(res.fileID)
                                        if (cuisineImgFileID.length == this.data.cuisineImg.length) {
                                                this.setData({
                                                        cuisineImgID: cuisineImgFileID,
                                                })
                                                this.addData()
                                        }
                                })
                                .catch(err => {
                                        wx.hideLoading()
                                        console.log('上传图片失败:', err)
                                        wx.showToast({
                                                title: '上传图片失败!',
                                                icon: 'none',
                                                duration: 1000,
                                        })
                                })
    }
};
   
/**
       * 添加数据
       */
        async function addData() {
                wx.showLoading({
                        title: '添加中...',
                        mask: true,
                })
                await db.collection('SysCuisine').add({
                                data: {
                                        cuisineImg: this.data.cuisineImgID,
                                        cuisineName: this.data.cuisineName,
                                },
                                success: res => {
                                        wx.hideLoading()
                                        if (res.errMsg == "collection.add:ok") {
                                                console.log('添加成功:', res.errMsg)
                                                wx.navigateBack({
                                                        delta: 1,
                                                })
                                        }
                                },
                                fail: err => {
                                        wx.hideLoading()
                                        console.log('添加失败:', err)
                                        let img = this.data.cuisineImgID
                                        console.log('添加失败,要删除的图片:', img)
                                        wx.cloud.deleteFile({
                                                fileList: img, //deleteFile的fileList是数组才能删除
                                                success: res => {
                                                        if (res.errMsg == "cloud.deleteFile:ok") {
                                                                wx.showToast({
                                                                        title: '添加失败!',
                                                                        icon: 'none',
                                                                        duration: 1000,
                                                                })
                                                        }
                                                },
                                                fail: err => {
                                                        wx.showToast({
                                                                title: '添加失败!',
                                                                icon: 'none',
                                                                duration: 1000,
                                                        })
                                                }
                                        })
                                }
                        })
        }
}
现在碰到的问题是当我按下确认按钮时并不能上传菜系,toast返回Invalid response from server,能帮我看看问题出在哪吗
@FishC

FishC 发表于 2023-12-19 16:56:08

看代码应该是云函数返回的结果不符合预期引起的。根据你提供的代码,似乎云函数在上传图片和添加数据时,都使用了this关键字来访问data中的数据。然而,云函数中没有上下文对象,也就是没有this关键字。

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

具体来说,修改addImg如下:

async function addImg(cuisineImg, name) {
    // ...
}

修改addData如下:

async function addData(cuisineImgID, cuisineName) {
    // ...
}

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

addImg函数中的数据

await wx.cloud.uploadFile({
    cloudPath,
    filePath: fileName,
}).then(res => {
    // ...
})

修改为

await wx.cloud.uploadFile({
    cloudPath,
    filePath: fileName,
}).then(res => {
    // ...
})

addData函数中的数据

await db.collection('SysCuisine').add({
    data: {
      cuisineImg: this.data.cuisineImgID,
      cuisineName: this.data.cuisineName,
    },
    success: res => {
      // ...
    },
    fail: err => {
      // ...
    }
})

修改为

await db.collection('SysCuisine').add({
    data: {
      cuisineImg: cuisineImgID,
      cuisineName: cuisineName,
    },
    success: res => {
      // ...
    },
    fail: err => {
      // ...
    }
})

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

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
页: [1]
查看完整版本: 微信小程序报错