
ตัวอย่างโค้ด nodejs api login สำหรับล็อกอิน
มาดูตัวอย่างการสร้าง api login ใน nodejs
ไปดูโค้ดกันเลย
const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const app = express();
app.use(express.json());
const users = [
{
id: 1,
username: 'admin',
password: '$2b$10$JTb1.9tZp.t6RKj7L/v1hu5h7VdZjK3q1z5vE0fXlzHZ5g5L5F5U6' // hashed password
}
];
const secretKey = 'secretkey';
app.post('/login', async (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username);
if (!user) return res.status(400).send({ error: 'Invalid username or password' });
try {
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) return res.status(400).send({ error: 'Invalid username or password' });
} catch (error) {
return res.status(500).send({ error: 'Server error' });
}
const token = jwt.sign({ id: user.id }, secretKey);
res.send({ token });
});
app.listen(3000, () => console.log('Server running on port 3000'));
จากตัวอย่าง เราใช้ app.post('/login', ...) เพื่อสร้าง API แบบ POST โดยมี /login เป็น endpoint
แล้วก็รับ username กับ password จาก request body
จากนั้นเราก็ไปค้น users ว่ามีหรือเปล่า ถ้าไม่มีก็ response 400 Bad Request กลับไป
ตัวอย่างเราใช้ bcrypt.compare() เพื่อ compare password ว่าได้ login ถูกต้องไหม ถ้าไม่ถูกก็ response 400 Bad Request กลับไป
ถ้าถูกต้องเราก็ส่ง jwt โดยใช้ jwt.sign กลับไป