这是微信小程序代码:Page({
data: {
primaryCategories: [], // 一级分类数据
secondaryCategories: [], // 二级分类数据
products: [], // 商品数据
currentPrimaryIndex: 0, // 当前选中的一级分类下标
currentSecondaryIndex: 0, // 当前选中的二级分类下标
scrollLeft: 0, // 一级分类滚动距离
currentTab: 0,
sleft: "", //横向滚动条位置
list: [1, 2, 3, 4, 5, 6, 7, 22, 32],//测试列表
},
handleTabChange(e) {
let { current } = e.target.dataset;
if (this.data.currentTab == current || current === undefined) return;
this.setData({
currentTab: current,
});
},
handleSwiperChange(e) {
this.setData({
currentTab: e.detail.current,
});
this.getScrollLeft();
},
getScrollLeft() {
const query = wx.createSelectorQuery();
query.selectAll(".item").boundingClientRect();
query.exec((res) => {
let num = 0;
for (let i = 0; i < this.data.currentTab; i++) {
num += res[0][i].width;
}
this.setData({
sleft: Math.ceil(num),
});
});
},
onLoad: function () {
// 获取一级分类列表
this.getPrimaryCategories();
},
// 获取一级分类列表
getPrimaryCategories: function () {
wx.request({
url: 'http://47.95.170.40:12345/primary_categories',
success: (res) => {
this.setData({ primaryCategories: res.data });
// 默认获取第一个一级分类下的二级分类和商品列表
this.getSecondaryCategories(res.data[0].id);
},
fail: (err) => {
console.error('Failed to fetch primary categories:', err);
}
});
},
// 获取二级分类列表和对应商品列表
getSecondaryCategories: function (primaryCategoryId) {
wx.request({
url: `http://47.95.170.40:12345/secondary_categories/${primaryCategoryId}`,
success: (res) => {
this.setData({ secondaryCategories: res.data });
// 默认获取第一个二级分类下的商品列表
this.getProducts(res.data[0].id);
},
fail: (err) => {
console.error('Failed to fetch secondary categories:', err);
}
});
},
// 获取商品列表
getProducts: function (secondaryCategoryId) {
wx.request({
url: `http://47.95.170.40:12345/products/${secondaryCategoryId}`,
success: (res) => {
// 处理数据,将商品图片和销量信息提取出来
let products = res.data.map(product => {
return {
id: product.id,
name: product.name,
price: product.price,
image: product.image,
sales: product.sales
};
});
this.setData({ products: products });
},
fail: (err) => {
console.error('Failed to fetch products:', err);
}
});
},
// 切换一级分类
switchPrimaryCategory: function (e) {
const index = e.currentTarget.dataset.index;
if (index !== this.data.currentPrimaryIndex) {
this.setData({ currentPrimaryIndex: index });
// 滚动到当前选中的一级分类
this.scrollToCurrentPrimary(index);
// 获取当前一级分类下的二级分类和商品列表
this.getSecondaryCategories(this.data.primaryCategories[index].id);
}
},
// 滚动到当前选中的一级分类
scrollToCurrentPrimary: function (index) {
const query = wx.createSelectorQuery();
query.select('#primary_' + index).boundingClientRect((rect) => {
this.setData({ scrollLeft: rect.left });
}).exec();
},
// 切换二级分类
switchSecondaryCategory: function (e) {
const index = e.currentTarget.dataset.index;
if (index !== this.data.currentSecondaryIndex) {
this.setData({ currentSecondaryIndex: index });
// 获取当前选中的二级分类下的商品列表
this.getProducts(this.data.secondaryCategories[index].id);
}
}
});
后端代码// 引入模块
const express = require('express');
const mysql = require('mysql');
const cors = require('cors');
const bodyParser = require('body-parser'); // 添加 body-parser 模块
// 创建 Express 应用程序
const app = express();
// 添加 CORS 中间件
app.use(cors());
app.use(bodyParser.json()); // 解析 application/json 类型的请求体
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
const pool = mysql.createPool({
connectionLimit: 10,
host: 'rm-2zek11k5v10a854i7.mysql.rds.aliyuncs.com',
port: 3306,
user: 'zangsa',
password: '******',
database: 'dome'
});
// 检查数据库链接是否出错,出错尝试重连
function handleDisconnect() {
pool.getConnection((err, connection) => {
if (err) {
console.log('Error when connecting to db:', err);
setTimeout(handleDisconnect, 3000);
return;
}
connection.on('error', (err) => {
console.log('DB error', err);
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
console.log('Reconnecting to the database...');
handleDisconnect();
} else {
throw err;
}
});
// 如果连接恢复正常,则加载应用配置并释放连接
connection.on('connect', () => {
console.log('Database connection established');
loadAppConfig(connection, () => {
// 在配置加载完成后释放连接
connection.release();
});
});
});
}
// 加载应用配置
function loadAppConfig(connection, callback) {
// 从数据库中读取配置项
connection.query('SELECT * FROM app_config', (error, results, fields) => {
if (error) {
console.log('Error loading app config:', error);
return;
}
// 将配置存储在全局变量中
appConfig = results[0];
console.log('App config loaded successfully:', appConfig);
// 执行回调函数
if (callback) {
callback();
}
});
}
// 初始化时调用一次
handleDisconnect();
// 默认访问路径
app.get('/', (req, res) => {
const text = '请求地址成功';
res.send(text);
});
// 获取一级分类列表接口
app.get('/primary_categories', (req, res) => {
pool.getConnection((err, connection) => {
if (err) {
console.log('Error getting primary categories:', err);
res.status(500).json({ error: 'Error getting primary categories' });
return;
}
connection.query('SELECT * FROM primary_categories', (error, results, fields) => {
connection.release();
if (error) {
console.log('Error fetching primary categories:', error);
res.status(500).json({ error: 'Error fetching primary categories' });
return;
}
res.json(results);
});
});
});
// 获取二级分类列表接口
app.get('/secondary_categories/:primaryCategoryId', (req, res) => {
const primaryCategoryId = req.params.primaryCategoryId;
pool.getConnection((err, connection) => {
if (err) {
console.log('Error getting secondary categories:', err);
res.status(500).json({ error: 'Error getting secondary categories' });
return;
}
connection.query('SELECT * FROM secondary_categories WHERE primary_category_id = ?', [primaryCategoryId], (error, results, fields) => {
connection.release();
if (error) {
console.log('Error fetching secondary categories:', error);
res.status(500).json({ error: 'Error fetching secondary categories' });
return;
}
res.json(results);
});
});
});
// 获取商品列表接口
app.get('/products/:secondaryCategoryId', (req, res) => {
const secondaryCategoryId = req.params.secondaryCategoryId;
pool.getConnection((err, connection) => {
if (err) {
console.log('Error getting products:', err);
res.status(500).json({ error: 'Error getting products' });
return;
}
connection.query('SELECT * FROM products WHERE secondary_category_id = ?', [secondaryCategoryId], (error, results, fields) => {
connection.release();
if (error) {
console.log('Error fetching products:', error);
res.status(500).json({ error: 'Error fetching products' });
return;
}
res.json(results);
});
});
});
// 获取商品详情接口
app.get('/product_details/:productId', (req, res) => {
const productId = req.params.productId;
pool.getConnection((err, connection) => {
if (err) {
console.log('Error getting product details:', err);
res.status(500).json({ error: 'Error getting product details' });
return;
}
connection.query('SELECT * FROM product_details WHERE product_id = ?', [productId], (error, results, fields) => {
connection.release();
if (error) {
console.log('Error fetching product details:', error);
res.status(500).json({ error: 'Error fetching product details' });
return;
}
res.json(results[0]);
});
});
});
// 监听请求
app.use((req, res, next) => {
console.log('请求来自于', req.get('Host'));
next();
});
const PORT = 12345;
app.listen(PORT, () => {
console.log(`服务器启动成功了,请求地址为:http://47.95.170.40:${PORT}`);
});
服务器文件夹权限也没问题,路径没问题。。。。https://
什么原因