gpt4 book ai didi

javascript - js如何让一个变量值根据用户登录 Node 存在

转载 作者:行者123 更新时间:2023-12-03 03:45:30 27 4
gpt4 key购买 nike

在我的 Node js 应用程序中,我有一个用户登录 api。上面我在服务器端代码中创建了一个名为 customerid 的变量。现在,当用户身份验证成功时。我将他的 userid 值存储在我的 customerid 变量中,我想使用它贯穿我的应用程序的变量。

但是我当前面临的问题是,当某人第一次登录时。它正在按预期的用户ID存储在customerid中并执行相关操作。但是当另一个人登录时,第一人的customerid被发送登录customerid覆盖,其中应该是这样。每个用户都应该只获取他相关的登录用户 ID 作为客户 ID。我怎样才能完成这项工作。下面是我的代码

var customerid;
app.post('/api/validate',function(req,res,callback){
customerid = '';
var datareq = req.body;
var data = {};
data.customerid = datareq.customerid;
request.post({
url:'https://databasedata.mybluemix.net/verifycredentials',
headers:{
'Content-Type':'application/json'
},
body:data,
json:true
},function(err,res,body){
verifycreds(body);
});

function verifycreds(data){
if(data.length == 0){
res.send("invalid username");
window.alert('Invalid user');
}
else if(data.length > 0){
if((datareq.customerid === data[0].customerid ) && (datareq.password ==
data[0].password)){
customerid = datareq.customerid;
res.send("valid");
}
else{
res.send("invalid");
}
}
}
});

最佳答案

Install cookie parser dependency and use it.
You can set it in res cookie once and use everywhere in other API.
Like this

var cookieParser = require("cookie-parser");
app.use(cookieParser());

app.post('/api/validate', function(req, res, callback) {
var datareq = req.body;
var data = {};
data.customerid = datareq.customerid;
request.post({
url: 'https://databasedata.mybluemix.net/verifycredentials',
headers: {
'Content-Type': 'application/json'
},
body: data,
json: true
}, function(err, response, body) {
verifycreds(body, response);
});

function verifycreds(data) {
if (data.length == 0) {
res.send("invalid username");
window.alert('Invalid user');
} else if (data.length > 0) {
if ((datareq.customerid === data[0].customerid) && (datareq.password == data[0].pa

ssword)) {
res.cookie('customerid', datareq.customerid);
res.send("valid");
} else {
res.send("invalid");
}
}
}
});


app.get('/api/home', function(req, res, callback) {
var customerid = req.cookies.customerid;
// get customerid as like this in every call

});

In other API take that customer id as req.cookies.customerid from req.

关于javascript - js如何让一个变量值根据用户登录 Node 存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45407887/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com