-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
65 lines (56 loc) · 1.71 KB
/
Copy pathindex.js
File metadata and controls
65 lines (56 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const BLOG = require('./models/blog');
const app = express();
const PORT = process.env.PORT || 8080;
const dbURI = 'mongodb+srv://vince:vince123@cluster0.vycwj80.mongodb.net/BlogData?retryWrites=true&w=majority&appName=Cluster0';
// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Database connection
mongoose.connect(dbURI)
.then(() => console.log('Connected to DB'))
.catch(err => console.log(err));
// Routes
app.post('/add-blog', async (req, res) => {
try {
const { title, author, description } = req.body;
const save = new BLOG({
title: title,
author: author,
description: description,
});
console.log('Data received:', req.body);
await save.save();
res.status(201).send('Blog post created successfully');
} catch (err) {
console.log(err);
res.status(500).send('Internal server error');
}
});
app.get('/', async (req, res) => {
try {
const data = await BLOG.find();
const blogs = data.map(blog => ({
title: blog.title,
author: blog.author,
description: blog.description,
time: blog.createdAt
}));
res.render('index', {title: 'Home', blogs});
} catch (err) {
console.log(err);
}
});
app.get('/about', (req, res) => {
res.render('about', {title: 'About'});
});
app.get('/create', (req, res) => {
res.render('create', {title: 'New Blog'});
});
app.use((req, res) => {
res.render('404', {title: '404'});
});
// Export the app
module.exports.handler = app;