-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
84 lines (71 loc) · 2.33 KB
/
server.js
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const app = express();
app.use(bodyParser.json());
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/your_database_name', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => console.log('MongoDB connected'))
.catch(err => console.log(err));
// User Schema
const UserSchema = new mongoose.Schema({
name: String,
email: String,
password: String
});
// Blog Schema
const BlogSchema = new mongoose.Schema({
title: String,
content: String,
author: String,
createdAt: { type: Date, default: Date.now }
});
const User = mongoose.model('User', UserSchema);
const Blog = mongoose.model('Blog', BlogSchema);
// Registration Route
app.post('/register', async (req, res) => {
const { name, email, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({ name, email, password: hashedPassword });
try {
await newUser.save();
res.json({ message: "User registered successfully!" });
} catch (err) {
res.status(400).json({ error: "Error registering user" });
}
});
// Login Route
app.post('/login', async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (user && await bcrypt.compare(password, user.password)) {
const token = jwt.sign({ id: user._id }, 'your_secret_key');
res.json({ token });
} else {
res.status(401).json({ error: "Invalid credentials" });
}
});
// Blog Post Route
app.post('/submit-blog', async (req, res) => {
const { title, content, author } = req.body;
const newBlog = new Blog({ title, content, author });
try {
await newBlog.save();
res.json({ message: "Blog posted successfully!" });
} catch (err) {
res.status(400).json({ error: "Error posting blog" });
}
});
// Get Blogs Route
app.get('/blogs', async (req, res) => {
const blogs = await Blog.find();
res.json(blogs);
});
// Server running
app.listen(3000, () => {
console.log('Server running on port 3000');
});