【问题标题】:Add cookie to response object inside a get request in node JS?将cookie添加到节点JS中的get请求内的响应对象?
【发布时间】:2018-06-29 07:35:11
【问题描述】:

我正在尝试将 cookie 添加到不同 get 请求中的响应对象 (res)。但是,如果我尝试以下操作,它会给我一个错误,我无法在发送标头后设置标头。我假设通过调用“请求”我已经发送了标头,如何使用来自单独获取请求的数据将 cookie 添加到响应对象?同步性质也不允许我将数据保存在 get 请求之外。我正在使用 npm btw 的请求模块,谢谢。

/* GET home page. */
router.get('/', function(req, res, next) {
    process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0
    var status = "Not currently logged in.";
    if (req.cookies.token !== undefined) {
      status = "Currently Logged in.";
    }
    if (req.cookies.email !== undefined) {
      request('https://localhost:44338/api/customer/' + req.cookies.email 
      {json: true}, (err, response, body) => {
        res.cookie('user', body[0].customerID, {maxAge: 9000000});
        //console.log(body);
      });
    }
    res.render('index', { title: 'Mighty Morphin Store', data: "", status: status});
});

【问题讨论】:

    标签: node.js cookies request


    【解决方案1】:

    您必须在设置 cookie 后在回调函数中发送响应。

    /* GET home page. */
    router.get('/', function(req, res, next) {
        process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0
        var status = "Not currently logged in.";
        if (req.cookies.token !== undefined) {
          status = "Currently Logged in.";
        }
        if (req.cookies.email !== undefined) {
          request('https://localhost:44338/api/customer/' + req.cookies.email 
          {json: true}, (err, response, body) => {
            res.cookie('user', body[0].customerID, {maxAge: 9000000});
            //console.log(body);
            res.render('index', { title: 'Mighty Morphin Store', data: "", status: status});
          });
        }
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-08
      • 1970-01-01
      • 1970-01-01
      • 2016-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多