-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
84 lines (72 loc) · 2.11 KB
/
Copy pathindex.js
File metadata and controls
84 lines (72 loc) · 2.11 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
import express from "express";
import bodyParser from "body-parser";
import cors from "cors";
import mysql from "mysql2";
import dotenv from "dotenv"
import bcrypt from "bcryptjs"
dotenv.config()
const app = express ();
app.use(express.json());
app.use(cors());
app.options("*", cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/",(req, res) => {
return res.status(200).json({
message : "API ready"
})
})
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
// password: 'your_password',
database: 'test_magang'
});
// Connect to MySQL
db.connect((err) => {
if (err) {
throw err;
}
console.log('Connected to MySQL');
});
//register
app.post("/user", async(req, res) => {
const {username, password, name, email} = req.body
const hashPass = await bcrypt.hash(password, 15)
const sql = 'INSERT INTO user (username, password, name, email) VALUES (?, ?, ?, ?)';
const values = [username, hashPass, name, email];
db.query(sql, values, (err, result) => {
if (err) throw err;
res.json({userId:result.insertId });
});
})
//login
app.post("/login", async(req, res) => {
const {username, password} = req.body // base on req
const sql = 'SELECT * FROM user WHERE username = ?';
db.query(sql, [username], (err, result) => {
if (err) throw err;
if (result.length === 0){
return res.status(404).json({message : "User not Found"})
}else{
const isMatch = bcrypt.compare(password, result[0].password)
if (isMatch){
return res.status(200).json({
username : result[0].username,
name : result[0].name,
email : result[0].email
})
}
}
})
})
app.get("/user", async(req, res) => {
const sql = 'SELECT userId, username, name, email FROM user';
db.query(sql, (err, result) => {
return res.status(200).json({
result
})
})
})
app.listen(3000, () => {
console.log("server running on port 3000")
})