发送后无法设置headers。使用智威汤逊

Can't set headers after they are sent. using JWT

我正在尝试使用 JWT 创建身份验证,当我创建我的方法时,它是一个名为 verifyJWT () 的函数,它开始触发此错误...

注意:在构造这个函数并在路由中使用之前,我可以从容发送,问题是当我做res.status (200) .send ({auth: true, token: jwtToken});然后res.redirect ('/ home/ v1'); 不过真的不知道为什么会出现这个问题..

正确的用户认证方式和后续路由是什么?

登录路由器:

const { body } = require('express-validator/check');

module.exports = (app) => {
    app.route('/')
    .get((req, res) => { app.controllers.login.controller.redirectRouter(app, req, res) });

    app.route('/login')
    .get((req, res)  => { app.controllers.login.controller.login(app, req, res); })
    .post([
        body('username').isString().isLength({ min: 1 }).not().isEmpty(),
        body('password').isString().isLength({ min: 1 }).not().isEmpty()
    ], (req, res) => { app.controllers.login.controller.checkLoginForm(app, req, res); });

}

登录控制器路由器

const { validationResult } = require('express-validator/check');
const jwt = require('jsonwebtoken');

module.exports.redirectRouter = (app, req, res) => res.redirect('/login');

module.exports.login = (app, req, res) => { 
    const renderConfig = new app.models.services.utilities.Render("LOGIN", true);
    renderConfig.httpJSPResponseStatusCode = 200;

    res.render('login/view', renderConfig.config);
}

module.exports.checkLoginForm = (app, req, res) => {
    /** @description: RECEBE O RESULTADO DA VALIÇÃO DO FORMULÁRIO PELO {EXPRESS-VALIDATOR} */
    const errors = validationResult(req);

    /** @description: VERIFICA SE HOUVE ERRO NA VALIDAÇÃO DO FORMULÁRIO COM O {EXPRESS-VALIDATOR} */
    if (!errors.isEmpty()) {
        /** @description: CASO ALGUM DADO ESTEJA INCONSISTENTE RETORNA {ERROR: 401} DE {NÃO AUTORIZADO} */
        res.status(401).send("401 Não autorizado");
    } else {
        /** @description: CASO OS DADOS FOREM VÁLIDOS, ADICIONA OS VALORES DO BODY NAS VARIÁVEIS */
        const username = req.body.username,
              password = req.body.password;

        /** FUNÇÕES TEMPORÁRIAS */
        if(username === "1" && password === "1"){
            const userId = 10;
            const jwtToken = jwt.sign({ userId }, process.env.SECRET, {
                expiresIn: 300 // EXPIRA EM 5MIN
            });

            //res.status(200).send({ auth: true, token: jwtToken });
            res.redirect('/home/v1');
        } else {
            res.status(401).send("401 Não autorizado");
        }
    }


}

家用路由器

    const jwtClass = require('../../models/services/JWT/controller.js');

    module.exports = (app) => {
        app.route('/home/v1/')
        .get(jwtClass.verifyJWT, (req, res) => {
            console.log("é get")
            //app.controllers.home.controller.home(app, req, res);
        }).post(jwtClass.verifyJWT, (req, res) => {
            console.log("é post")
            //app.controllers.home.controller.home(app, req, res);
        });
    }

** HOME CONTROLLER ROUTER **
module.exports.home = (app, req, res) => {
    res.render('home/view');
}

JWT函数方法

const jwt = require('jsonwebtoken');

module.exports.verifyJWT = (req, res, next) => {
    const jwtToken = req.headers['x-access-token'];

    if (!jwtToken) {
        return res.status(401).send({ auth: false, message: 'No token provided.' });
    } else {
        jwt.verify(jwtToken, process.env.SECRET, (error, decoded) => {
            if (error) {
                return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
            } else {
                    console.log("ae")
                req.userId = decoded.id;
                next();
            }
        });
    }
}
 //res.status(200).send({ auth: true, token: jwtToken });
        res.redirect('/home/v1');

您无法在发送响应后重定向。请参考 REST 中请求和响应的工作方式 api。您在这里可以做的是先重定向,然后在重定向后发送 Auth Token(在重定向路由中)。您需要在重定向后写入登录名。

更新:

尝试添加行 res.status(200).send({ auth: true, token: jwtToken }); 家用路由器

里面

另外请将正确的模块导入到 HOME ROUTER。

    const jwtClass = require('../../models/services/JWT/controller.js');

    module.exports = (app) => {
        app.route('/home/v1/')
        .get(jwtClass.verifyJWT, (req, res) => {
            console.log("é get")
            //ADD HERE
          res.status(200).send({ auth: true, token: jwtToken });
            //app.controllers.home.controller.home(app, req, res);
        }).post(jwtClass.verifyJWT, (req, res) => {
            console.log("é post")
           //ADD HERE
            res.status(200).send({ auth: true, token: jwtToken });
            //app.controllers.home.controller.home(app, req, res);
        });
    }

** HOME CONTROLLER ROUTER **
module.exports.home = (app, req, res) => {
    res.render('home/view');
}