ExpressJS:这个逻辑已经正确了吗?

时间:2019-05-10 07:38:37

标签: node.js express

我创建了2个中间件,它们分别是authenticate.jsredirectedIfAuthenticated.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?因为我对自己的代码有些奇怪。顺便说一句,他们工作得很好

0 个答案:

没有答案