最后活跃于 1755883036

MisterFixx 修订了这个 Gist 1755883035. 转到此修订

1 file changed, 529 insertions

gpt-oss:20b.md(文件已创建)

@@ -0,0 +1,529 @@
1 + Below is a **minimal yet complete** CRUD REST API that:
2 +
3 + 1. **Creates / reads / updates / deletes** “items” in a MongoDB collection.
4 + 2. Uses **Express** as the web‑framework.
5 + 3. Stores data with **Mongoose** (MongoDB).
6 + 4. Secures the API with **JSON Web Tokens (JWT)** – users must sign‑up / log‑in, receive a token and include it in the `Authorization` header for all protected routes.
7 +
8 + Feel free to copy‑paste the files into a folder, run `npm install` and start the server.
9 +
10 + ---
11 +
12 + ## 1️⃣ Directory layout
13 +
14 + ```
15 + crud-jwt-api/
16 + ├─ .env
17 + ├─ package.json
18 + ├─ server.js
19 + ├─ config/
20 + │ └─ db.js
21 + ├─ models/
22 + │ ├─ User.js
23 + │ └─ Item.js
24 + ├─ middleware/
25 + │ └─ auth.js
26 + ├─ routes/
27 + │ ├─ auth.js
28 + │ └─ items.js
29 + └─ controllers/
30 + ├─ authController.js
31 + └─ itemController.js
32 + ```
33 +
34 + ---
35 +
36 + ## 2️⃣ `package.json`
37 +
38 + ```json
39 + {
40 + "name": "crud-jwt-api",
41 + "version": "1.0.0",
42 + "description": "CRUD REST API with Express, MongoDB & JWT auth",
43 + "main": "server.js",
44 + "scripts": {
45 + "start": "node server.js",
46 + "dev": "nodemon server.js"
47 + },
48 + "keywords": [],
49 + "author": "",
50 + "license": "ISC",
51 + "dependencies": {
52 + "bcrypt": "^5.1.0",
53 + "dotenv": "^16.3.1",
54 + "express": "^4.18.2",
55 + "jsonwebtoken": "^9.0.0",
56 + "mongoose": "^7.3.4"
57 + },
58 + "devDependencies": {
59 + "nodemon": "^3.0.1"
60 + }
61 + }
62 + ```
63 +
64 + > Run `npm install` first.
65 +
66 + ---
67 +
68 + ## 3️⃣ `.env`
69 +
70 + Create a `.env` file **at the project root**.
71 + Replace the placeholder values with your own.
72 +
73 + ```
74 + PORT=5000
75 + MONGO_URI=mongodb://localhost:27017/crud_jwt_api
76 + JWT_SECRET=supersecretkey123 # <-- keep this safe!
77 + JWT_EXPIRES_IN=1h
78 + ```
79 +
80 + > For a production environment you should store these in a secrets manager.
81 +
82 + ---
83 +
84 + ## 4️⃣ `server.js`
85 +
86 + ```js
87 + require('dotenv').config();
88 + const express = require('express');
89 + const connectDB = require('./config/db');
90 +
91 + const app = express();
92 +
93 + // Connect to MongoDB
94 + connectDB();
95 +
96 + // Middleware: parse JSON bodies
97 + app.use(express.json());
98 +
99 + // Routes
100 + app.use('/api/auth', require('./routes/auth'));
101 + app.use('/api/items', require('./routes/items'));
102 +
103 + // Global error handler (optional but handy)
104 + app.use((err, req, res, next) => {
105 + console.error(err.stack);
106 + res.status(500).json({ msg: 'Server Error' });
107 + });
108 +
109 + const PORT = process.env.PORT || 5000;
110 + app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));
111 + ```
112 +
113 + ---
114 +
115 + ## 5️⃣ Database connection – `config/db.js`
116 +
117 + ```js
118 + const mongoose = require('mongoose');
119 +
120 + const connectDB = async () => {
121 + try {
122 + await mongoose.connect(process.env.MONGO_URI, {
123 + // Options are optional in Mongoose 6+
124 + });
125 + console.log('MongoDB connected');
126 + } catch (err) {
127 + console.error(err.message);
128 + process.exit(1); // exit on DB connect failure
129 + }
130 + };
131 +
132 + module.exports = connectDB;
133 + ```
134 +
135 + ---
136 +
137 + ## 6️⃣ Mongoose models
138 +
139 + ### 6.1 User – `models/User.js`
140 +
141 + ```js
142 + const mongoose = require('mongoose');
143 + const bcrypt = require('bcrypt');
144 +
145 + const UserSchema = new mongoose.Schema({
146 + email: {
147 + type: String,
148 + required: true,
149 + unique: true,
150 + lowercase: true,
151 + trim: true,
152 + },
153 + password: { type: String, required: true, minlength: 6 },
154 + createdAt: { type: Date, default: Date.now },
155 + });
156 +
157 + // Pre‑save hook to hash password
158 + UserSchema.pre('save', async function (next) {
159 + if (!this.isModified('password')) return next();
160 + const salt = await bcrypt.genSalt(10);
161 + this.password = await bcrypt.hash(this.password, salt);
162 + next();
163 + });
164 +
165 + // Method to compare password
166 + UserSchema.methods.matchPassword = async function (enteredPassword) {
167 + return await bcrypt.compare(enteredPassword, this.password);
168 + };
169 +
170 + module.exports = mongoose.model('User', UserSchema);
171 + ```
172 +
173 + ### 6.2 Item – `models/Item.js`
174 +
175 + ```js
176 + const mongoose = require('mongoose');
177 +
178 + const ItemSchema = new mongoose.Schema({
179 + title: { type: String, required: true },
180 + description: { type: String },
181 + // Optional: link to owner
182 + owner: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
183 + createdAt: { type: Date, default: Date.now },
184 + });
185 +
186 + module.exports = mongoose.model('Item', ItemSchema);
187 + ```
188 +
189 + ---
190 +
191 + ## 7️⃣ JWT auth middleware – `middleware/auth.js`
192 +
193 + ```js
194 + const jwt = require('jsonwebtoken');
195 + const User = require('../models/User');
196 +
197 + const protect = async (req, res, next) => {
198 + let token;
199 + // Expected format: Authorization: Bearer <token>
200 + if (
201 + req.headers.authorization &&
202 + req.headers.authorization.startsWith('Bearer')
203 + ) {
204 + token = req.headers.authorization.split(' ')[1];
205 + }
206 +
207 + if (!token) {
208 + return res.status(401).json({ msg: 'Not authorized, token missing' });
209 + }
210 +
211 + try {
212 + const decoded = jwt.verify(token, process.env.JWT_SECRET);
213 + // Attach user to request (you could also only send _id)
214 + req.user = await User.findById(decoded.id).select('-password');
215 + next();
216 + } catch (err) {
217 + console.error(err);
218 + res.status(401).json({ msg: 'Not authorized, token invalid' });
219 + }
220 + };
221 +
222 + module.exports = { protect };
223 + ```
224 +
225 + ---
226 +
227 + ## 8️⃣ Auth routes & controller
228 +
229 + ### 8.1 `routes/auth.js`
230 +
231 + ```js
232 + const express = require('express');
233 + const router = express.Router();
234 + const { signup, login } = require('../controllers/authController');
235 +
236 + // POST /api/auth/signup
237 + router.post('/signup', signup);
238 +
239 + // POST /api/auth/login
240 + router.post('/login', login);
241 +
242 + module.exports = router;
243 + ```
244 +
245 + ### 8.2 `controllers/authController.js`
246 +
247 + ```js
248 + const User = require('../models/User');
249 + const jwt = require('jsonwebtoken');
250 +
251 + // Helper to create JWT
252 + const generateToken = (id) => {
253 + return jwt.sign({ id }, process.env.JWT_SECRET, {
254 + expiresIn: process.env.JWT_EXPIRES_IN || '1h',
255 + });
256 + };
257 +
258 + exports.signup = async (req, res) => {
259 + const { email, password } = req.body;
260 + if (!email || !password)
261 + return res.status(400).json({ msg: 'Please provide email & password' });
262 +
263 + try {
264 + // Check if user exists
265 + let user = await User.findOne({ email });
266 + if (user)
267 + return res.status(400).json({ msg: 'User already exists' });
268 +
269 + user = new User({ email, password });
270 + await user.save();
271 +
272 + const token = generateToken(user._id);
273 + res.status(201).json({
274 + token,
275 + user: { id: user._id, email: user.email },
276 + });
277 + } catch (err) {
278 + console.error(err);
279 + res.status(500).json({ msg: 'Server error' });
280 + }
281 + };
282 +
283 + exports.login = async (req, res) => {
284 + const { email, password } = req.body;
285 + if (!email || !password)
286 + return res.status(400).json({ msg: 'Please provide email & password' });
287 +
288 + try {
289 + const user = await User.findOne({ email });
290 + if (!user)
291 + return res.status(400).json({ msg: 'Invalid credentials' });
292 +
293 + const isMatch = await user.matchPassword(password);
294 + if (!isMatch)
295 + return res.status(400).json({ msg: 'Invalid credentials' });
296 +
297 + const token = generateToken(user._id);
298 + res.json({
299 + token,
300 + user: { id: user._id, email: user.email },
301 + });
302 + } catch (err) {
303 + console.error(err);
304 + res.status(500).json({ msg: 'Server error' });
305 + }
306 + };
307 + ```
308 +
309 + ---
310 +
311 + ## 9️⃣ Items routes & controller
312 +
313 + ### 9.1 `routes/items.js`
314 +
315 + ```js
316 + const express = require('express');
317 + const router = express.Router();
318 + const {
319 + getItems,
320 + getItem,
321 + createItem,
322 + updateItem,
323 + deleteItem,
324 + } = require('../controllers/itemController');
325 + const { protect } = require('../middleware/auth');
326 +
327 + // All routes below require a valid JWT
328 + router.use(protect);
329 +
330 + // GET /api/items
331 + router.get('/', getItems);
332 +
333 + // GET /api/items/:id
334 + router.get('/:id', getItem);
335 +
336 + // POST /api/items
337 + router.post('/', createItem);
338 +
339 + // PUT /api/items/:id
340 + router.put('/:id', updateItem);
341 +
342 + // DELETE /api/items/:id
343 + router.delete('/:id', deleteItem);
344 +
345 + module.exports = router;
346 + ```
347 +
348 + ### 9.2 `controllers/itemController.js`
349 +
350 + ```js
351 + const Item = require('../models/Item');
352 +
353 + // GET all items (you could paginate)
354 + exports.getItems = async (req, res) => {
355 + try {
356 + const items = await Item.find().sort({ createdAt: -1 });
357 + res.json(items);
358 + } catch (err) {
359 + console.error(err);
360 + res.status(500).json({ msg: 'Server error' });
361 + }
362 + };
363 +
364 + // GET single item
365 + exports.getItem = async (req, res) => {
366 + try {
367 + const item = await Item.findById(req.params.id);
368 + if (!item) return res.status(404).json({ msg: 'Item not found' });
369 + res.json(item);
370 + } catch (err) {
371 + console.error(err);
372 + res.status(500).json({ msg: 'Server error' });
373 + }
374 + };
375 +
376 + // CREATE new item
377 + exports.createItem = async (req, res) => {
378 + const { title, description } = req.body;
379 + if (!title) return res.status(400).json({ msg: 'Title is required' });
380 +
381 + try {
382 + const newItem = new Item({
383 + title,
384 + description,
385 + owner: req.user._id, // optional
386 + });
387 + await newItem.save();
388 + res.status(201).json(newItem);
389 + } catch (err) {
390 + console.error(err);
391 + res.status(500).json({ msg: 'Server error' });
392 + }
393 + };
394 +
395 + // UPDATE existing item
396 + exports.updateItem = async (req, res) => {
397 + const { title, description } = req.body;
398 + try {
399 + let item = await Item.findById(req.params.id);
400 + if (!item) return res.status(404).json({ msg: 'Item not found' });
401 +
402 + // optional: restrict update to owner only
403 + // if (!item.owner.equals(req.user._id))
404 + // return res.status(403).json({ msg: 'Not allowed' });
405 +
406 + item.title = title ?? item.title;
407 + item.description = description ?? item.description;
408 +
409 + await item.save();
410 + res.json(item);
411 + } catch (err) {
412 + console.error(err);
413 + res.status(500).json({ msg: 'Server error' });
414 + }
415 + };
416 +
417 + // DELETE item
418 + exports.deleteItem = async (req, res) => {
419 + try {
420 + const item = await Item.findById(req.params.id);
421 + if (!item) return res.status(404).json({ msg: 'Item not found' });
422 +
423 + // optional: restrict delete to owner only
424 + // if (!item.owner.equals(req.user._id))
425 + // return res.status(403).json({ msg: 'Not allowed' });
426 +
427 + await item.remove();
428 + res.json({ msg: 'Item removed' });
429 + } catch (err) {
430 + console.error(err);
431 + res.status(500).json({ msg: 'Server error' });
432 + }
433 + };
434 + ```
435 +
436 + ---
437 +
438 + ## 🔑 10️⃣ Using the API
439 +
440 + Below are example `curl` calls. Replace `localhost:5000` with your host if different.
441 +
442 + ### 10.1 Sign‑up
443 +
444 + ```bash
445 + curl -X POST http://localhost:5000/api/auth/signup \
446 + -H "Content-Type: application/json" \
447 + -d '{"email":"[email protected]","password":"secret123"}'
448 + ```
449 +
450 + Response contains a JWT (`token`) and the user object.
451 +
452 + ### 10.2 Log‑in
453 +
454 + ```bash
455 + curl -X POST http://localhost:5000/api/auth/login \
456 + -H "Content-Type: application/json" \
457 + -d '{"email":"[email protected]","password":"secret123"}'
458 + ```
459 +
460 + > Save the `token` from the response.
461 +
462 + ### 10.3 Create an item
463 +
464 + ```bash
465 + curl -X POST http://localhost:5000/api/items \
466 + -H "Content-Type: application/json" \
467 + -H "Authorization: Bearer <YOUR_TOKEN>" \
468 + -d '{"title":"My first item","description":"Hello world!"}'
469 + ```
470 +
471 + ### 10.4 Get all items
472 +
473 + ```bash
474 + curl -X GET http://localhost:5000/api/items \
475 + -H "Authorization: Bearer <YOUR_TOKEN>"
476 + ```
477 +
478 + ### 10.5 Get a single item
479 +
480 + ```bash
481 + curl -X GET http://localhost:5000/api/items/<ITEM_ID> \
482 + -H "Authorization: Bearer <YOUR_TOKEN>"
483 + ```
484 +
485 + ### 10.6 Update an item
486 +
487 + ```bash
488 + curl -X PUT http://localhost:5000/api/items/<ITEM_ID> \
489 + -H "Content-Type: application/json" \
490 + -H "Authorization: Bearer <YOUR_TOKEN>" \
491 + -d '{"title":"Updated title"}'
492 + ```
493 +
494 + ### 10.7 Delete an item
495 +
496 + ```bash
497 + curl -X DELETE http://localhost:5000/api/items/<ITEM_ID> \
498 + -H "Authorization: Bearer <YOUR_TOKEN>"
499 + ```
500 +
501 + ---
502 +
503 + ## ⚙️ 11️⃣ Things to improve for production
504 +
505 + | Area | Suggestion |
506 + |------|------------|
507 + | **Password policy** | Enforce stronger passwords, use OWASP guidelines. |
508 + | **Rate limiting / brute‑force protection** | Add `express-rate-limit`. |
509 + | **Refresh tokens** | Store a long‑lived refresh token in a cookie or DB. |
510 + | **HTTPS** | Use TLS in front of the API. |
511 + | **CORS** | Configure properly (`cors` package). |
512 + | **Input validation** | Use `express-validator` or `Joi`. |
513 + | **Logging** | Use Winston / Morgan with log rotation. |
514 + | **Testing** | Add unit / integration tests (`jest` / `supertest`). |
515 + | **Docker** | Containerise the app & MongoDB for reproducibility. |
516 +
517 + ---
518 +
519 + ### 🎉 You’re done!
520 +
521 + This example covers the core concepts:
522 +
523 + - **User signup & login** → JWT issuance
524 + - **Middleware** → protects routes
525 + - **CRUD** on a resource
526 + - **Mongoose** data modelling
527 + - **Error handling** basics
528 +
529 + Feel free to extend it—add pagination, sorting, file uploads, or any other feature you need. Happy coding!
上一页 下一页