四季网

四季网

天天酷跑大黄鸭代码

admin
天天酷跑大黄鸭代码 # 部署环境 - Linux 操作系统 - Node.js v10 或更高版本 - MongoDB 数据库 # 安装依赖库 ```bash npm install --save express mongoose ``` # 创建 Express 应用程序 在项目目录中创建一个名为 `app.js` 的文件,并将以下代码粘贴进去: ```javascript const express = require('express'); const mongoose = require('mongoose'); const app = express(); const port = 3000; mongoose.connect('mongodb://localhost/天天酷跑了', { useNewUrlParser: true, useUnifiedTopology: true }); app.get('/', (req, res) => { res.send('天天酷跑大黄鸭 API'); }); app.listen(port, () => { console.log(`天天酷跑大黄鸭 API 正在监听端口 ${port}`); }); ``` # 创建数据模型 在同一个项目目录中创建一个名为 `duck.js` 的文件,并将以下代码粘贴进去: ```javascript const mongoose = require('mongoose'); const duckSchema = new mongoose.Schema({ name: { type: String, required: true }, color: { type: String, required: true }, size: { type: Number, required: true } }); module.exports = mongoose.model('Duck', duckSchema); ``` # 定义 API 路由 在 `app.js` 文件中添加以下 API 路由: ```javascript const Duck = require('./duck'); app.get('/api/ducks', async (req, res) => { const ducks = await Duck.find(); res.json(ducks); }); app.post('/api/ducks', async (req, res) => { const duck = new Duck(req.body); await duck.save(); res.json(duck); }); app.put('/api/ducks/:id', async (req, res) => { const duck = await Duck.findByIdAndUpdate(req.params.id, req.body, { new: true }); res.json(duck); }); app.delete('/api/ducks/:id', async (req, res) => { await Duck.findByIdAndDelete(req.params.id); res.json({ message: '大黄鸭已删除' }); }); ``` # 启动应用程序 在终端中运行以下命令启动应用程序: ```bash node app.js ``` # API 端点 - 获取所有大黄鸭:`GET /api/ducks` - 创建新大黄鸭:`POST /api/ducks` - 更新现有大黄鸭:`PUT /api/ducks/:id` - 删除大黄鸭:`DELETE /api/ducks/:id` # 示例请求 获取所有大黄鸭: ```bash curl -X GET http://localhost:3000/api/ducks ``` 输出: ```json [ { "_id": "5f041822f264871034fb3e66", "name": "小黄", "color": "黄色", "size": 10 }, { "_id": "5f041822f264871034fb3e67", "name": "大黄", "color": "黄色", "size": 15 } ] ``` 创建新大黄鸭: ```bash curl -X POST http://localhost:3000/api/ducks -H 'Content-Type: application/json' -d '{"name": "超级大黄鸭", "color": "黄色", "size": 20}' ``` 输出: ```json { "_id": "5f041822f264871034fb3e68", "name": "超级大黄鸭", "color": "黄色", "size": 20 } ``` 更新现有大黄鸭: ```bash curl -X PUT http://localhost:3000/api/ducks/5f041822f264871034fb3e68 -H 'Content-Type: application/json' -d '{"name": "终极大黄鸭", "size": 25}' ``` 输出: ```json { "_id": "5f041822f264871034fb3e68", "name": "终极大黄鸭", "color": "黄色", "size": 25 } ``` 删除大黄鸭: ```bash curl -X DELETE http://localhost:3000/api/ducks/5f041822f264871034fb3e68 ``` 输出: ```json { "message": "大黄鸭已删除" } ```