exports.main = async (event, context) => {
const axios = require('axios');
try {
const response = await axios.get('https://5b243195.r2.cpolar.top/api/get-garbage-data');
if (response.status === 200) {
const garbageData = response.data;
const db = cloud.database();
const result = await Promise.all(garbageData.map(item => {
return db.collection('garbage').add({
data: {
type: item.type,
name: item.name,
}
});
}));
console.log('数据成功保存到云数据库:', result);
return {
success: true,
result: result,
message: '数据已成功保存到云数据库'
};
} else {
console.error('获取数据失败,HTTP状态码:', response.status);
return {
success: false,
message: '获取数据失败,HTTP状态码:' + response.status
};
}
} catch (e) {
console.error('处理远程请求时发生错误:', e);
return {
success: false,
message: '处理远程请求时发生错误:' + e.message
};
}
};
小程序端的index.js
Page({
data: {
garbageList: [],
operationStatus: '',
errorMessage: '',
},
onLoad: function(options) {
this.fetchAndSaveGarbageData();
},
fetchAndSaveGarbageData: function() {
wx.cloud.callFunction({
name: 'fetchAndSaveGarbageData',
data: {},
}).then(res => {
if (res.result && res.result.success) {
this.setData({
operationStatus: 'success',
garbageList: res.result.result,
errorMessage: res.result.message || '',
});
console.log('数据获取并保存成功:', res.result);
} else {
this.setData({
operationStatus: 'error',
errorMessage: res.result ? res.result.message : '未知错误',
});
console.error('数据获取失败:', res.result ? res.result.message : '未知错误');
}
}).catch(err => {
this.setData({
operationStatus: 'error',
errorMessage: '云函数调用失败:' + err.message,
});
console.error('云函数调用失败:', err);
});
},
});
全靠猜?啥问题也不说吗
这不跟没说一样,复制下标题,有啥意义