- Регистрация
- 1 Мар 2015
- Сообщения
- 1,481
- Баллы
- 155
This guide teaches how to build a simple Blog Article CRUD API using:
1. Create a folder and initialize npm:
mkdir blog-crud && cd blog-crud
npm init -y
2. Install required packages:
npm install express mongoose body-parser
Organize your project files like this:
blog-crud/
├── models/
│ └── Article.js # Mongoose schema
├── routes/
│ └── articles.js # Route handlers
├── server.js # Main app entry
├── package.json
? Step 3: Create the Express Server (server.js)
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const articleRoutes = require('./routes/articles');
const app = express();
// Middleware to parse JSON
app.use(bodyParser.json());
// Route prefix: All article routes will start with /api/articles
app.use('/api/articles', articleRoutes);
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/blog_crud', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => console.log('
MongoDB Connected'))
.catch(err => console.error('
DB Connection Error:', err));
// Start the server
app.listen(3000, () => console.log('? Server running at http://localhost:3000'));
Explanation:
const mongoose = require('mongoose');
const articleSchema = new mongoose.Schema({
title: String,
content: String,
author: String,
createdAt: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Article', articleSchema);
Explanation:
const express = require('express');
const router = express.Router();
const Article = require('../models/Article');
? 1. Create a new Article (POST /api/articles)
router.post('/', async (req, res) => {
try {
const article = await Article.create(req.body);
res.status(201).json(article);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
router.get('/', async (req, res) => {
try {
const articles = await Article.find();
res.json(articles);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
router.get('/:id', async (req, res) => {
try {
const article = await Article.findById(req.params.id);
if (!article) return res.status(404).json({ message: 'Not found' });
res.json(article);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
router.put('/:id', async (req, res) => {
try {
const updated = await Article.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true } // return the updated document
);
if (!updated) return res.status(404).json({ message: 'Not found' });
res.json(updated);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
router.delete('/:id', async (req, res) => {
try {
const deleted = await Article.findByIdAndDelete(req.params.id);
if (!deleted) return res.status(404).json({ message: 'Not found' });
res.json({ message: '
Article deleted' });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
const express = require('express');
const router = express.Router();
const Article = require('../models/Article');
//
Create an article
router.post('/', async (req, res) => {
try {
const article = await Article.create(req.body);
res.status(201).json(article);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// ? Get all articles
router.get('/', async (req, res) => {
try {
const articles = await Article.find();
res.json(articles);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// ? Get a single article by ID
router.get('/:id', async (req, res) => {
try {
const article = await Article.findById(req.params.id);
if (!article) return res.status(404).json({ message: 'Not found' });
res.json(article);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
//
Update an article
router.put('/:id', async (req, res) => {
try {
const updated = await Article.findByIdAndUpdate(req.params.id, req.body, { new: true });
if (!updated) return res.status(404).json({ message: 'Not found' });
res.json(updated);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
//
Delete an article
router.delete('/:id', async (req, res) => {
try {
const deleted = await Article.findByIdAndDelete(req.params.id);
if (!deleted) return res.status(404).json({ message: 'Not found' });
res.json({ message: 'Article deleted' });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
module.exports = router;
? Step 6: Testing the API
Use tools like Postman, Insomnia, or curl:
curl -X POST \
-H "Content-Type: application/json" \
-d '{"title": "My First Blog", "content": "Hello world!", "author": "Xavier"}'
curl
curl <article_id>
curl -X PUT <article_id> \
-H "Content-Type: application/json" \
-d '{"title": "Updated Title"}'
curl -X DELETE <article_id>
Final Notes
- Node.js – runtime to run JavaScript on the server
- Express – web framework for building APIs
- MongoDB – NoSQL database
- Mongoose – MongoDB ODM (object-document mapper)
1. Create a folder and initialize npm:
mkdir blog-crud && cd blog-crud
npm init -y
2. Install required packages:
npm install express mongoose body-parser
- express: Web framework
- mongoose: Connect and interact with MongoDB
- body-parser: Parse incoming JSON request bodies
Organize your project files like this:
blog-crud/
├── models/
│ └── Article.js # Mongoose schema
├── routes/
│ └── articles.js # Route handlers
├── server.js # Main app entry
├── package.json
? Step 3: Create the Express Server (server.js)
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const articleRoutes = require('./routes/articles');
const app = express();
// Middleware to parse JSON
app.use(bodyParser.json());
// Route prefix: All article routes will start with /api/articles
app.use('/api/articles', articleRoutes);
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/blog_crud', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => console.log('
.catch(err => console.error('
// Start the server
app.listen(3000, () => console.log('? Server running at http://localhost:3000'));
Explanation:
- This is your main app file.
- It sets up Express, connects to MongoDB, and loads article routes.
const mongoose = require('mongoose');
const articleSchema = new mongoose.Schema({
title: String,
content: String,
author: String,
createdAt: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Article', articleSchema);
Explanation:
- Defines the structure of each Blog Article in the database.
- Includes fields like title, content, author, and createdAt.
const express = require('express');
const router = express.Router();
const Article = require('../models/Article');
? 1. Create a new Article (POST /api/articles)
router.post('/', async (req, res) => {
try {
const article = await Article.create(req.body);
res.status(201).json(article);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
? 2. Read All Articles (GET /api/articles)Accepts JSON { title, content, author } and stores it in the database.
router.get('/', async (req, res) => {
try {
const articles = await Article.find();
res.json(articles);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
? 3. Read a Single Article by ID (GET /api/articles/:id)Returns all articles stored in the database.
router.get('/:id', async (req, res) => {
try {
const article = await Article.findById(req.params.id);
if (!article) return res.status(404).json({ message: 'Not found' });
res.json(article);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
? 4. Update an Article (PUT /api/articles/:id)Fetches a specific article using its ID.
router.put('/:id', async (req, res) => {
try {
const updated = await Article.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true } // return the updated document
);
if (!updated) return res.status(404).json({ message: 'Not found' });
res.json(updated);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
? 5. Delete an Article (DELETE /api/articles/:id)Edits article details like title or content.
router.delete('/:id', async (req, res) => {
try {
const deleted = await Article.findByIdAndDelete(req.params.id);
if (!deleted) return res.status(404).json({ message: 'Not found' });
res.json({ message: '
} catch (err) {
res.status(500).json({ error: err.message });
}
});
Finally routes/articles.jsDeletes the selected article from the database.
const express = require('express');
const router = express.Router();
const Article = require('../models/Article');
//
router.post('/', async (req, res) => {
try {
const article = await Article.create(req.body);
res.status(201).json(article);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// ? Get all articles
router.get('/', async (req, res) => {
try {
const articles = await Article.find();
res.json(articles);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// ? Get a single article by ID
router.get('/:id', async (req, res) => {
try {
const article = await Article.findById(req.params.id);
if (!article) return res.status(404).json({ message: 'Not found' });
res.json(article);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
//
router.put('/:id', async (req, res) => {
try {
const updated = await Article.findByIdAndUpdate(req.params.id, req.body, { new: true });
if (!updated) return res.status(404).json({ message: 'Not found' });
res.json(updated);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
//
router.delete('/:id', async (req, res) => {
try {
const deleted = await Article.findByIdAndDelete(req.params.id);
if (!deleted) return res.status(404).json({ message: 'Not found' });
res.json({ message: 'Article deleted' });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
module.exports = router;
? Step 6: Testing the API
Use tools like Postman, Insomnia, or curl:
- Create:
curl -X POST \
-H "Content-Type: application/json" \
-d '{"title": "My First Blog", "content": "Hello world!", "author": "Xavier"}'
- Read All:
curl
- Read One:
curl <article_id>
- Update:
curl -X PUT <article_id> \
-H "Content-Type: application/json" \
-d '{"title": "Updated Title"}'
- Delete:
curl -X DELETE <article_id>
- Make sure MongoDB is running locally (mongodb://localhost:27017)
- Keep practicing with different data
- You can later connect this API to a front-end using React or Vue