如何从浏览器获取控制器文件中的 cookie 值,或者如何从一个节点文件获取从一个节点文件到另一个节点文件的可变传递



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

身份验证控制器.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');
}
}
});
};

现在在卡控制器中.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,我是节点的新手,因此任何帮助都将得到认可 我们可以以某种方式将数据从一个控制器文件共享到另一个文件吗?

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

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

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

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

让我告诉你,如果你想将JWT存储到cookie和其他额外的信息中,它可以被存储或不存储,这取决于你的cookie的大小。

有关 Cookie 最大大小的更多信息,请查看以下内容:https://www.quora.com/What-Is-The-Maximum-Size-Of-Cookie-In-A-Web-Browser

另一方面,我在您的实现中看到了一个问题,我建议您在下面:

如果您正在接收 JWT,您将保留 JWT 身份验证器的性质。

https://medium.com/@siddharthac6/json-web-token-jwt-the-right-way-of-implementing-with-node-js-65b8915d550e

最新更新