Node.js blog application structured using the MVC (Model-View-Controller) architecture.
1. **Project Structure:**
```
/blog_app
/controllers
postController.js
/models
postModel.js
/views
postView.js
/routes
postRoutes.js
app.js
```
2. **Setup Dependencies:**
You'll need to initialize a Node.js project and install necessary dependencies, such as Express and any database-related libraries (e.g., Mongoose for MongoDB).
```bash
npm init -y
npm install express mongoose
```
3. **Model:**
In `postModel.js`, define the Post model using Mongoose or any other ORM/ODM library you prefer.
```javascript
const mongoose = require('mongoose');
const postSchema = new mongoose.Schema({
title: String,
content: String,
date: {
type: Date,
default: Date.now
}
});
const Post = mongoose.model('Post', postSchema);
module.exports = Post;
```
4. **Controller:**
In `postController.js`, handle the business logic for blog posts.
```javascript
const Post = require('../models/postModel');
exports.getAllPosts = async (req, res) => {
try {
const posts = await Post.find();
res.json(posts);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
exports.createPost = async (req, res) => {
const post = new Post({
title: req.body.title,
content: req.body.content
});
try {
const newPost = await post.save();
res.status(201).json(newPost);
} catch (error) {
res.status(400).json({ message: error.message });
}
};
```
5. **Routes:**
In `postRoutes.js`, define the routes for handling post-related requests.
```javascript
const express = require('express');
const router = express.Router();
const postController = require('../controllers/postController');
router.get('/posts', postController.getAllPosts);
router.post('/posts', postController.createPost);
module.exports = router;
```
6. **Views:**
Views can be HTML files or templates rendered by the server. For simplicity, let's just handle JSON responses. In `postView.js`, you could define any view-related logic.
```javascript
// postView.js
// This file could contain any logic related to rendering posts,
// such as formatting post data before sending it to the client.
```
7. **App.js:**
Finally, in `app.js`, set up the Express application and connect routes.
```javascript
const express = require('express');
const mongoose = require('mongoose');
const postRoutes = require('./routes/postRoutes');
const app = express();
app.use(express.json());
// Connect to MongoDB
mongoose.connect('mongodb://localhost/blog_app', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => console.log('Connected to MongoDB'));
// Routes
app.use('/api', postRoutes);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
```
Now, you have a basic Node.js blog application following the MVC architecture. You can expand it by adding more controllers, models, views, and routes as needed. Additionally, you can incorporate features like authentication, pagination, or frontend templating engines like EJS or Handlebars for rendering HTML views.
0 Comments