Blog Platform with Custom CMS

Step 1: Set Up the Project


Blog Platform with Custom CMS

Step 1: Set Up the Project

  1. Initialize your project:
mkdir custom-blog cd custom-blog npm init -y
  1. Install necessary packages:
npm install express mongoose body-parser ejs

Step 2: Create Basic Folder Structure





Step 3: Set Up the MongoDB Connection

Create a new file named app.js and set up the Express app with MongoDB:

javascriptCopy code// app.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const postRoutes = require('./routes/posts');

const app = express();

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/custom-blog', {
useNewUrlParser: true,
useUnifiedTopology: true
});

// Middleware
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));

// Routes
app.use('/posts', postRoutes);

app.get('/', (req, res) => {
res.redirect('/posts');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});


Step 4: Create the Post Model

Create a file named Post.js inside the models directory:

javascriptCopy code// models/Post.js
const mongoose = require('mongoose');

const postSchema = new mongoose.Schema({
title: { type: String, required: true },
content: { type: String, required: true },
createdAt: { type: Date, default: Date.now }
});

module.exports = mongoose.model('Post', postSchema);


Step 5: Set Up Routes for Posts

Create a file named posts.js inside the routes directory:

javascriptCopy code// routes/posts.js
const express = require('express');
const Post = require('../models/Post');
const router = express.Router();

// Get all posts
router.get('/', async (req, res) => {
const posts = await Post.find();
res.render('index', { posts });
});

// Create a new
  1. Initialize your project:
mkdir custom-blog cd custom-blog npm init -y
  1. Install necessary packages:
npm install express mongoose body-parser ejs

Step 2: Create Basic Folder Structure

plaintextCopy codecustom-blog/
│
├── models/
│   └── Post.js
├── routes/
│   └── posts.js
├── views/
│   ├── index.ejs
│   └── post.ejs
├── public/
│   └── styles.css
├── app.js
└── package.json

Step 3: Set Up the MongoDB Connection

Create a new file named app.js and set up the Express app with MongoDB:

javascriptCopy code// app.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const postRoutes = require('./routes/posts');

const app = express();

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/custom-blog', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

// Middleware
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));

// Routes
app.use('/posts', postRoutes);

app.get('/', (req, res) => {
    res.redirect('/posts');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

Step 4: Create the Post Model

Create a file named Post.js inside the models directory:

javascriptCopy code// models/Post.js
const mongoose = require('mongoose');

const postSchema = new mongoose.Schema({
    title: { type: String, required: true },
    content: { type: String, required: true },
    createdAt: { type: Date, default: Date.now }
});

module.exports = mongoose.model('Post', postSchema);

Step 5: Set Up Routes for Posts

Create a file named posts.js inside the routes directory:

javascriptCopy code// routes/posts.js
const express = require('express');
const Post = require('../models/Post');
const router = express.Router();

// Get all posts
router.get('/', async (req, res) => {
    const posts = await Post.find();
    res.render('index', { posts });
});

// Create a new post
router.get('/new', (req, res) => {
    res.render('post', { post: {} });
});

router.post('/', async (req, res) => {
    const { title, content } = req.body;
    const post = new Post({ title, content });
    await post.save();
    res.redirect('/posts');
});

// View a single post
router.get('/:id', async (req, res) => {
    const post = await Post.findById(req.params.id);
    res.render('post', { post });
});

module.exports = router;

Step 6: Create Views

index.ejs

htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Blog</title>
    <link rel="stylesheet" href="/styles.css">
</head>
<body>
    <h1>Blog Posts</h1>
    <a href="/posts/new">Create New Post</a>
    <ul>
        <% posts.forEach(post => { %>
            <li>
                <a href="/posts/<%= post._id %>"><%= post.title %></a>
            </li>
        <% }) %>
    </ul>
</body>
</html>

post.ejs

htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><%= post.title || 'New Post' %></title>
</head>
<body>
    <h1><%= post.title || 'Create a New Post' %></h1>
    <form action="/posts<%= post._id ? '/' + post._id : '' %>" method="POST">
        <input type="text" name="title" placeholder="Title" value="<%= post.title %>" required>
        <textarea name="content" placeholder="Content" required><%= post.content %></textarea>
        <button type="submit">Save Post</button>
    </form>
    <a href="/posts">Back to posts</a>
</body>
</html>

Step 7: Add Basic Styling

Create a file named styles.css inside the public directory:

cssCopy code/* public/styles.css */
body {
    font-family: Arial, sans-serif;
}

h1 {
    color: #333;
}

a {
    text-decoration: none;
    color: blue;
}

ul {
    list-style: none;
    padding: 0;
}

li {
    margin: 10px 0;
}

Step 8: Run Your Application

  1. Start your MongoDB server (if you’re using a local instance):bashCopy codemongod
  2. Run your Express app:bashCopy codenode app.js

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *