Untitled
unknown
javascript
2 years ago
1.3 kB
10
Indexable
const cors = require("cors");
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
app.use(express.json());
const secretKey = 'your-secret-key';
const users = [];
app.use(
cors({
origin: "*", // allow requests from any other server
})
);
app.post('/register', (req, res) => {
const { username, password } = req.body;
// Kiểm tra xem người dùng có tồn tại trong danh sách không
const userExists = users.some(user => user.username === username);
if (userExists) {
res.status(400).json({ message: 'User already exists' });
} else {
users.push({ username, password });
const token = jwt.sign({ username }, secretKey, { expiresIn: '1h' });
res.json({ token });
}
});
app.post('/login', (req, res) => {
const { username, password } = req.body;
// Kiểm tra xem người dùng có tồn tại và mật khẩu đúng không
const user = users.find(user => user.username === username && user.password === password);
if (user) {
const token = jwt.sign({ username }, secretKey, { expiresIn: '1h' });
res.json({ token, message: 'success' });
} else {
res.status(401).json({ message: 'fail' });
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Editor is loading...