首页 > 解决方案 > 如何从浏览器获取控制器文件中的 cookie 值或如何从一个节点文件获取可变传递到另一个节点文件

问题描述

我正在使用 express 创建一个身份验证系统,现在我已经对用户进行了身份验证,并将他的电子邮件保存在控制器文件中的 cookie 中,一旦用户在另一个控制器中获得身份验证,我需要该 cookie 值,但我无法访问它

验证-controller.js

var Cryptr = require('cryptr');
cryptr = new Cryptr('myTotalySecretKey');
var express = require('express');
const ap = express();
var jwt = require('jsonwebtoken');
var connection = require('./../../config');
var localStorage = require('localStorage');
const cookieParser = require('cookie-parser');


module.exports.authenticate = function (req, res) {
    var email = req.body.email;
    var password = req.body.password;


    connection.query('SELECT * FROM users WHERE email = ?', [email], function (error, results, fields) {
        if (error) {
            res.json({
                status: false,
                message: 'there are some error with query'
            });
        } else {

            if (results.length > 0) {
                decryptedString = cryptr.decrypt(results[0].password);
                if (password == decryptedString) {
                    jwt.sign({ email, password },
                        'secretkey',
                        { expiresIn: '10days' },
                        (err, token) => {
                            console.log('token:' + token);
                            module.exports = token;
                            console.log(token);
                            res.cookie('jwt', token);
                            res.cookie('Auth', 'true');
                            res.cookie('UName', email);
                            res.redirect('/../home.html');

                        }

                    );


                } else {
                    res.redirect('/Authentication/login.html');
                    console.log("Wrong Input");

                }

            }
            else {
                res.redirect('/Authentication/login.html');
            }
        }
    });
};

现在在 card-controller.js 我想访问那个 cookie 所以我用这个

let connection = require('/home/codemymobile/study/trello/config');
let Cryptr = require('cryptr');
let express = require("express");
const cookieParser = require('cookie-parser');
var email = Cookies.get('UName');
module.exports.card = function (req, res) {

};

但是我的节点显示错误 cookie 未定义,我对节点很陌生,所以任何帮助都会得到帮助,我们可以以某种方式将数据从一个控制器文件共享到另一个文件吗?

标签: node.jsexpress

解决方案


好的,关于您的第二个代码片段,我注意到了几件事。

您正在使用您对 cookieParser 变量产生影响的 cookie-parser 包,但是在您使用之后,Cookies.get但我看不到Cookies来自哪里?所以也许你想要做的是cookieParser.get但是通过检查 cookie-parser 包我没有看到任何get方法所以在这里很难帮助你。

除此之外,您应该能够通过req.cookies在您的函数中使用来查看您的 cookie。

我希望它会对你有所帮助......


推荐阅读