我创建了2个中间件,它们分别是authenticate.js
和redirectedIfAuthenticated.js
,所以重点是我想为它们制作一个优化且可扩展的中间件,但是我不知道这是否正确。
他们在这里:
./app/middleware/authenticate.js
'use strict';
import jwt from 'jsonwebtoken';
export default (req, res, next) => {
jwt.verify(req.headers['x-access-token'], req.app.get('secretKey'), (err, decoded) => {
if (err) {
res.status(400).send({
status: 'Error',
message: err.message,
data: null
});
} else {
req.body.id = decoded.id;
next();
}
});
}
./app/middleware/redirectedIfAuthenticated.js
'use strict';
import jwt from 'jsonwebtoken';
export default (req, res, next) => {
jwt.verify(req.headers['x-access-token'], req.app.get('secretKey'), (err, decoded) => {
if (err) {
next();
} else {
res.status(400).send({
message: 'User already login',
});
}
});
};
./routes/index.js
'use strict';
import AuthenticateMiddleware from './../app/middleware/authenticate';
import redirectedIfAuthenticated from './../app/middleware/redirectedIfAuthenticated';
import express from 'express';
import AuthRoutes from './auth';
import UserRoutes from './user';
const app = express();
app.use('/auth', redirectedIfAuthenticated, AuthRoutes);
app.use('/user', AuthenticateMiddleware, UserRoutes);
app.all('*', (req, res) => {
res.status(404).send({
message: `${req} not found`
});
});
export default app;
问题是我在做什么已经正确了? AuthRoutes
?因为我对自己的代码有些奇怪。顺便说一句,他们工作得很好