webs/nicetechcg/server/index.js

38 lines
982 B
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const express = require('express');
const jwt = require('jsonwebtoken');
const { expressjwt: jwtMiddleware } = require('express-jwt'); // 导入 express-jwt 中间件
const app = express();
const secret = 'nicetechsg';
// 中间件:保护所有 /api 路由
app.use(
'/api',
jwtMiddleware({ secret, algorithms: ['HS512'] })
);
app.get("/test", (req, res) =>{
res.json({message: "test"})
})
// 登录接口(生成 token
app.post('/login', (req, res) => {
const user = { password: 1, username: 'alice' };
const token = jwt.sign(user, secret, { expiresIn: '1h' });
res.json({ token });
});
// 受保护接口
app.get('/api/protected', (req, res) => {
res.json({ message: 'You have access!', user: req.auth });
});
// 错误处理
app.use((err, req, res, next) => {
if (err.name === 'UnauthorizedError') {
return res.status(401).json({ message: 'Invalid token' });
}
next(err);
});
app.listen(3000, () => console.log('Server started on port 3000'));