You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
1.1 KiB
51 lines
1.1 KiB
4 months ago
|
const express = require('express')
|
||
|
const bodyParser = require('body-parser')
|
||
|
const app = express()
|
||
|
|
||
|
app.use(bodyParser.json())
|
||
|
|
||
|
// 模拟数据库
|
||
|
let users = []
|
||
|
|
||
|
app.post('/api/register', (req, res) => {
|
||
|
const { username, password } = req.body
|
||
|
if (users.some(u => u.username === username)) {
|
||
|
return res.status(400).json({ message: '用户已存在' })
|
||
|
}
|
||
|
|
||
|
const newUser = {
|
||
|
id: Date.now(),
|
||
|
username,
|
||
|
password, // 实际项目需要加密存储
|
||
|
createdAt: new Date().toISOString()
|
||
|
}
|
||
|
|
||
|
users.push(newUser)
|
||
|
res.json({
|
||
|
token: 'mock-jwt-token',
|
||
|
user: newUser
|
||
|
})
|
||
|
})
|
||
|
|
||
|
app.post('/api/login', (req, res) => {
|
||
|
const { username, password } = req.body
|
||
|
const user = users.find(u => u.username === username)
|
||
|
|
||
|
if (!user || user.password !== password) {
|
||
|
return res.status(401).json({ message: '用户名或密码错误' })
|
||
|
}
|
||
|
|
||
|
res.json({
|
||
|
token: 'mock-jwt-token',
|
||
|
user
|
||
|
})
|
||
|
})
|
||
|
|
||
|
app.get('/api/user', (req, res) => {
|
||
|
// 实际需要验证token
|
||
|
res.json(users[0] || {})
|
||
|
})
|
||
|
|
||
|
app.listen(3000, () => {
|
||
|
console.log('Mock API服务器运行在 http://localhost:8080')
|
||
|
})
|