-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
80 lines (62 loc) · 2.09 KB
/
server.js
File metadata and controls
80 lines (62 loc) · 2.09 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// server.js
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
const PORT = 5004;
// Middleware
app.use(cors());
app.use(express.json());
// Connect to MongoDB
mongoose.connect('mongodb://127.0.0.1:27017/civilbridge', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('✅ MongoDB connected to civilbridge'))
.catch(err => console.error('❌ MongoDB connection error:', err));
const userSchema = new mongoose.Schema({
name: String,
email: String,
phone: String,
address: String,
password: String
});
const User = mongoose.model('User', userSchema); // Bound to 'users'
// Registration Route
app.post('/register', async (req, res) => {
const { name, email, phone, address, password } = req.body;
if (!name || !email || !phone || !address || !password) {
return res.status(400).json({ message: 'All fields are required' });
}
try {
const exists = await User.findOne({ email });
if (exists) {
return res.status(409).json({ message: 'User already exists' });
}
const user = new User({ name, email, phone, address, password });
await user.save();
res.status(201).json({ message: 'Registration successful' });
} catch (err) {
console.error('Registration error:', err);
res.status(500).json({ message: 'Server error' });
}
});
app.post('/login', async (req, res) => {
const { email, password } = req.body;
if (!email?.trim() || !password?.trim()) {
return res.status(400).json({ message: 'Email and password required' });
}
try {
const user = await User.findOne({ email, password });
if (!user) {
return res.status(401).json({ message: 'Invalid credentials' });
}
res.json({ message: 'Login successful', name: user.name });
} catch (err) {
console.error('Login error:', err);
res.status(500).json({ message: 'Server error' });
}
});
app.listen(PORT, () => {
console.log(`🚀 Server running at http://localhost:${PORT}`);
});