-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
64 lines (52 loc) · 1.46 KB
/
server.js
File metadata and controls
64 lines (52 loc) · 1.46 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
const express = require('express')
const mongoose = require('mongoose')
require('dotenv').config()
const User = require('./models/User')
const bcrypt = require('bcryptjs')
const app = express()
const PORT = 3000
app.use(express.json());
//Home page api
app.get('/', (req, res) =>
res.send('Hello World ON')
)
//Registering page api
app.post('/register',async(req, res) => {
const {username, email, password} = req.body
try {
const hashedPassword = await bcrypt.hash(password, 10)
const user = new User({username,email, password: hashedPassword})
await user.save()
res.json({message: "User registered.."})
console.log("User registration completed...")
} catch (err) {
console.log(err)
}
})
//Login page api
app.post('/login',async(req,res)=>{
const {email, password} = req.body
try{
const user = await User.findOne({email});
if(!user || !(await bcrypt.compare(password, user.password)))
{
return res.status(400).json({message: "Invalid credentials"});
}
res.json({message: "Login successful..", username: user.username});
}
catch(err){
console.log(err)
}
}
)
mongoose.connect(process.env.MONGO_URL).then(
() =>console.log("DB connected successfully..")
).catch(
(err) => console.log(err))
app.listen(PORT, (err) => {
if (err) {
console.log(err)
} else {
console.log("Server is running on port :"+PORT)
}
})