基于Vue+Nodejs宠物领养系统
时间: 2025-06-24 22:35:42 浏览: 14
### Vue 和 Node.js 构建宠物领养系统的解决方案
以下是基于 Vue 和 Node.js 实现宠物领养系统的一个基本架构和代码示例:
#### 后端部分 (Node.js)
后端主要负责处理 API 请求以及数据库交互。
##### 1. 初始化项目
创建一个新的 Node.js 项目并安装依赖项:
```bash
npm init -y
npm install express mongoose cors body-parser dotenv
```
##### 2. 创建服务器文件 `server.js`
```javascript
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
// 连接 MongoDB 数据库
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/petAdoption', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const app = express();
app.use(cors());
app.use(bodyParser.json());
// 定义 Pet Schema
const petSchema = new mongoose.Schema({
name: String,
breed: String,
age: Number,
adoptedBy: { type: String, default: null },
}, { timestamps: true });
const Pet = mongoose.model('Pet', petSchema);
// 获取所有宠物
app.get('/pets', async (req, res) => {
try {
const pets = await Pet.find();
res.status(200).json(pets);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
// 领养宠物
app.put('/pets/:id/adopt', async (req, res) => {
try {
const updatedPet = await Pet.findByIdAndUpdate(
req.params.id,
{ adoptedBy: req.body.name },
{ new: true }
);
res.status(200).json(updatedPet);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
```
---
#### 前端部分 (Vue.js)
前端主要用于展示宠物列表并与用户互动。
##### 1. 初始化 Vue 项目
使用 Vue CLI 或 Vite 创建一个新项目:
```bash
vue create pet-adoption-system
cd pet-adoption-system
npm install axios
```
##### 2. 编写组件逻辑
###### 文件结构
```
src/
├── components/
│ ├── PetsList.vue
│ └── AdoptForm.vue
└── App.vue
```
###### 组件实现
**PetsList.vue**
显示宠物列表。
```html
<template>
<div class="pets-list">
<h2>Available Pets</h2>
<ul>
<li v-for="pet in pets" :key="pet._id">
{{ pet.name }} | Breed: {{ pet.breed }} | Age: {{ pet.age }}
<button @click="adoptPet(pet._id)" v-if="!pet.adoptedBy">Adopt Me!</button>
<span v-else>(Already adopted by {{ pet.adoptedBy }})</span>
</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
pets: [],
};
},
methods: {
fetchPets() {
axios.get('http://localhost:3000/pets')
.then(response => this.pets = response.data)
.catch(error => console.error(error));
},
adoptPet(id) {
const name = prompt('Enter your name:');
if (!name.trim()) return;
axios.put(`http://localhost:3000/pets/${id}/adopt`, { name })
.then(() => this.fetchPets())
.catch(error => alert('Error adopting the pet'));
},
},
mounted() {
this.fetchPets();
},
};
</script>
```
**App.vue**
作为根组件加载子组件。
```html
<template>
<div id="app">
<h1>Pet Adoption System</h1>
<PetsList />
</div>
</template>
<script>
import PetsList from './components/PetsList.vue';
export default {
components: { PetsList },
};
</script>
```
---
### 功能扩展建议
为了进一步完善此系统,可以考虑以下功能改进[^2]:
1. **用户登录注册**: 使用 JWT 或 OAuth 提供身份验证机制。
2. **宠物详情页面**: 展示每只宠物更详细的描述信息。
3. **图片上传支持**: 用户可以通过表单上传宠物照片。
4. **通知提醒**: 当有新的宠物加入或被领养时发送邮件或短信给管理员。
5. **数据持久化优化**: 将敏感操作日志存储到数据库以便审计追踪。
---
阅读全文
相关推荐


















