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

标签 javascript node.js

在我的 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/

相关文章:

javascript - 过渡移动文本后如何使文本可见

node.js - 如何在客户端正确显示服务器请求的数据

mongodb - 使用 MongoDB 在 Node.js 中定义 `model` 的正确方法是什么?

node.js - Sailsjs Model.update 在 Controller 中不起作用

java - 如何在 Velocity 模板中获取 Liferay Portlet 实例 ID

javascript - 调整游戏音乐的音量

javascript - 如何将现代版本的 Vue (Vue CLI3) 与 Electron 结合使用?

javascript - 无法在 beforeCreate Hook 中设置日期 - Strapi (beta14)

javascript - 如何获取克隆选项的选择属性?

javascript - 调整 javascript 行