-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
82 lines (72 loc) · 2.3 KB
/
app.js
File metadata and controls
82 lines (72 loc) · 2.3 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
81
82
// Required modules
const express = require('express');
const mongoose = require('mongoose');
const path = require('path');
const app = express();
// Middleware
app.use(express.static('public')); // Serve static files (HTML, CSS, JS)
app.use(express.json()); // Parse incoming JSON requests
// MongoDB connection
mongoose.connect('mongodb+srv://Ayush:IT0QzoQgnQxVPI4k@cluster0.dtuxkcw.mongodb.net/userdb?retryWrites=true&w=majority&appName=Cluster0', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('Connected to MongoDB'))
.catch((error) => console.error('Error connecting to MongoDB:', error));
// Define the user schema and model
const usrSchema = new mongoose.Schema({
user_name: {
type: String,
required: true,
},
Password: {
type: String,
required: true,
}
});
const User = mongoose.model('user', usrSchema);
app.get('/',async(req,res)=>{
try{
res.redirect('/login.html');
}catch(error){
window.write("Cannot reach login.html");
}
})
// POST route to handle user signup
app.post('/signup', async (req, res) => {
try {
const data = req.body;
const usr = new User(data); // Create new user instance
await usr.save(); // Save the user to MongoDB
res.status(201).send(); // Send a success response
} catch (error) {
console.error('Error saving user:', error);
res.status(500).send('Error creating account'); // Send an error response
}
});
app.post('/login', async(req,res) => {
try{
const {user_name,Password} = req.body;
const name = await User.findOne({user_name});
if(name){
// console.log('name is matched');
// console.log(Password+ ""+name.Password);
if(name.Password=== Password){
// console.log('Ayush');
return res.status(200).send();
}
return res.status(401).send();
}else{
return res.status(404).send();
// console.log('failed if');
}
}catch(error){
// console.log('failed try');
return res.status(404).send();
}
})
// Define a port and start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});