接着昨天发布的(一)县城小时达即时配送系统编程教程:从零构建高效本地配送平台开始后续的后端 API 开发
4. 后端 API 开发
4.1 用户注册与登录
js复制代码// 用户注册 API
app.post('/api/users/register', async (req, res) => {
const { name, phone, address } = req.body;
const newUser = new User({ name, phone, address });
await newUser.save();
res.json({ message: 'Registration successful', userId: newUser._id });
});
// 用户登录 API
app.post('/api/users/login', async (req, res) => {
const { phone } = req.body;
const user = await User.findOne({ phone });
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.json({ message: 'Login successful', userId: user._id });
});
4.2 商品浏览与下单
js复制代码// 获取商家商品
app.get('/api/vendors/:vendorId/products', async (req, res) => {
const vendor = await Vendor.findById(req.params.vendorId);
res.json(vendor.products);
});
// 用户下单 API
app.post('/api/orders', async (req, res) => {
const { userId, vendorId, productList, address } = req.body;
const totalPrice = calculateTotalPrice(productList);
const newOrder = new Order({
user_id: userId,
vendor_id: vendorId,
product_list: productList,
status: 'waiting',
address,
total_price: totalPrice,
});
await newOrder.save();
res.json({ message: 'Order placed successfully', orderId: newOrder._id });
});
function calculateTotalPrice(productList) {
let total = 0;
productList.forEach(item => {
total += item.quantity * item.price;
});
return total;
}
4.3 配送员接单与配送
js复制代码// 配送员接单
app.post('/api/couriers/accept-order', async (req, res) => {
const { courierId, orderId } = req.body;
const order = await Order.findById(orderId);
if (order.status !== 'waiting') {
return res.status(400).json({ message: 'Order already in progress' });
}
order.status = 'in_progress';
order.assigned_courier = courierId;
await order.save();
res.json({ message: 'Order accepted', orderId: order._id });
});
5. 实时配送与导航
为了实现配送员的实时导航与路线规划,可以利用 高德地图 API 来为配送员提供路线规划和实时位置追踪。
配送员位置更新与导航
js复制代码// 配送员位置更新
app.post('/api/couriers/update-location', async (req, res) => {
const { courierId, lat, lng } = req.body;
const courier = await Courier.findById(courierId);
courier.location = { lat, lng };
await courier.save();
res.json({ message: 'Location updated successfully' });
});
// 获取配送路线
app.post('/api/couriers/get-route', async (req, res) => {
const { startLat, startLng, endLat, endLng } = req.body;
// 使用高德地图API获取路线数据
const route = await getRouteFromAmap(startLat, startLng, endLat, endLng);
res.json(route);
});
async function getRouteFromAmap(startLat, startLng, endLat, endLng) {
// 调用高德地图API(示例代码)
const response = await fetch(`https://restapi.amap.com/v3/direction/driving?origin=${startLng},${startLat}&destination=${endLng},${endLat}&key=高德地图API密钥`);
const data = await response.json();
return data.route;
}
6. 前端开发
前端开发是整个系统的展示部分,下面以用户端(Vue.js)为例来说明开发流程。
用户端功能开发
商品展示
<template>
<div>
<h2>商品列表</h2>
<ul>
<li v-for="product in products" :key="product._id">
<span>{{ product.name }} - ¥{{ product.price }}</span>
<button @click="addToCart(product)">添加到购物车</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
products: [],
};
},
mounted() {
fetch('/api/vendors/1/products')
.then(res => res.json())
.then(data => {
this.products = data;
});
},
methods: {
addToCart(product) {
// 添加到购物车
},
},
};
</script>
下单与支付
<template>
<div>
<button @click="placeOrder">确认下单</button>
</div>
</template>
<script>
export default {
methods: {
placeOrder() {
const order = {
userId: '用户ID',
vendorId: '商家ID',
productList: this.cartItems,
address: '送货地址',
};
fetch('/api/orders', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(order),
}).then(res => res.json())
.then(data => {
alert('下单成功');
});
},
},
};
</script>
通过上述步骤,我们从数据库设计到后端API,再到前端展示,完整地构建了一个县城小时达的即时配送系统。这个系统的核心是高效的订单处理与配送员管理,能够实现快速响应并提供高质量的服务。
为了提升系统的扩展性和优化性能,我们可以进一步引入消息队列来处理高并发订单、使用Redis缓存商品信息和订单数据、引入自动化测试和CI/CD流程等。