一种持久化为加密生成的相同/唯一id的方法.在nodeJS上的用户随机uid ?



我正在开发一个web应用程序,我需要给用户一个唯一的ID为他,我搜索并使用加密模块来生成UUID,它的工作原理,这里是代码(我发送它与我的res.render的产品)。

import Product from '../models/Products';
const crypto = require('crypto');
const getProducts = async (req, res) => {
const products = await Product.find().lean();
const idValueUser = crypto.randomUUID();
console.log(idValueUser);
res.render('products/products', { layout: 'products-lyt',
products: products, 
userId: idValueUser});
};

module.exports = getProducts;

我通过渲染将userId传递给手柄文件,并在文件的javascript中将该Id传递给本地存储:

<div class="container-fluid products-container">
<div class="products-columns">
{{#each products}}
{{> products-partial }}
{{/each}}
</div>

<p id="awadetest">{{userId}}</p>
</div>
<script>
var testeo = document.getElementById("awadetest").innerHTML;
console.log(testeo);
localStorage.setItem("test", testeo);
</script>

Id正确传递到localStorage(我将发送到数据库后的表单),但问题是,每次用户重新加载(使请愿到产品的页面)的Id改变(逻辑上),但我需要一种方法,使该Id持续存在,所以我可以识别用户在数据库后,有人知道一种方法来做到这一点?或者如果存在更好的方法来识别用户,而不意味着登录或使用IP,顺便说一句,谢谢

如果对某人有帮助,我让解决方案对我有用(比我想象的更容易):

基本上是在本地存储(或cookie,如果您正在使用它)上进行验证,如下所示:

window.onload = function () {
var testeo = document.getElementById("awadetest").innerHTML;

if (localStorage.getItem("userId") == null){
localStorage.setItem("userId", testeo);
}
else{
return;
}
}
有了这个,代码可以很容易地识别浏览器是否已经有一个userId(我在不同的浏览器上测试,它的工作,为每个浏览器生成不同的代码)。如果有人遇到了同样的"问题";您可以将我(在购物车中识别用户)添加到"表单"中;这是发送到DB的userId从本地存储,希望它帮助某人