How to Build a Node.js Blog API with HTML Output
Introduction
In this tutorial, you’ll learn how to build a complete Blog API using Node.js, Express, and MongoDB, with server-side rendered HTML views using EJS
. This Blog API will allow you to add and list blog posts using a web interface.
Step 1: Project Setup
Create a folder and initialize a Node.js project:
mkdir mavenbird-blog-api cd mavenbird-blog-api npm init -y npm install express mongoose ejs body-parser
Step 2: File Structure
Use the following file structure:
mavenbird-blog-api/ ├── server.js ├── models/Post.js ├── routes/blog.js ├── views/index.ejs ├── public/style.css
Step 3: Create MongoDB Schema
File: models/Post.js
const mongoose = require('mongoose'); const PostSchema = new mongoose.Schema({ title: String, content: String, date: { type: Date, default: Date.now } }); module.exports = mongoose.model('Post', PostSchema);
Step 4: Create Express Server
File: server.js
const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const blogRoutes = require('./routes/blog'); const app = express(); const PORT = 3000; mongoose.connect('mongodb://localhost:27017/mavenbird_blog', { useNewUrlParser: true, useUnifiedTopology: true }); app.set('view engine', 'ejs'); app.use(express.static('public')); app.use(bodyParser.urlencoded({ extended: true })); app.use('/', blogRoutes); app.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}`); });
Step 5: Define Blog Routes
File: routes/blog.js
const express = require('express'); const router = express.Router(); const Post = require('../models/Post'); router.get('/', async (req, res) => { const posts = await Post.find().sort({ date: -1 }); res.render('index', { posts }); }); router.get('/add', (req, res) => { res.send('<form method="POST" action="/add"> ... </form>'); }); router.post('/add', async (req, res) => { const { title, content } = req.body; await Post.create({ title, content }); res.redirect('/'); }); module.exports = router;
Step 6: Render Posts with HTML
File: views/index.ejs
<!DOCTYPE html>
<html>
<head><title>Mavenbird Blog</title></head>
<body>
<h1>Mavenbird Blog</h1>
<a href="/add">Add New Post</a>
<% posts.forEach(post => { %>
<div>
<h2><%= post.title %></h2>
<p><%= post.content %></p>
<small><%= post.date.toDateString() %></small>
</div>
<% }) %>
</body>
</html>
Conclusion
Congratulations! You’ve built a basic blog API in Node.js using Express and MongoDB, with HTML rendering using EJS. You can expand this by adding edit/delete routes, authentication, or a rich text editor.
Need Help? Contact us at Contact Mavenbird today.
Please complete your information below to login.