无法访问通过节点请求传递的某些数据

时间:2019-03-19 00:18:46

标签: node.js express microservices

我会说我已经在做这项工作,但是在上周的某个地方,它变得一团糟,我似乎无法追踪到做到这一点的提交。

我正在使用Node and Express创建微服务,其中一些代码可能不值一提(笑)。我的想法是,我有一个自定义API网关,该网关使用Request将请求转发到我的后端服务。为此,我使用函数设置了选项,然后使用options重设了req.user的一部分,以便可以访问其他后端服务中的用户信息。

用于请求的选项

options = {
  baseUrl : serviceURL, // Ignore this part it is because I am using multiple instances of my backend services. 
  form: {'':''}, // This is where I am going to pass in the user info below
  headers: {authorization: ''}
}

路线/终点

// POST USER/SETTINGS/NOTIFICATION
router.post('/user/settings/notification',  
isAuthenticated('all'), (req, res) => { // This line authenticates and authorizes the user. It also attaches the user model/data to req.user
  options.form = req.body;
  options.form.user = req.user; // Here I set the user data to be accessible
  request.post(req.path, options, (error, response, body) => {
    if (error) throw error;
    res.status(response.statusCode).send(body);
  });
});

输出

{
  foo: 'bar', // This is my other data
  'user[company][stripe][isCoupon]': 'false',
  'user[isVerified]': 'true',
  'user[_id]': '5c8d2a0c2f1f881e2377a601',
  'user[email]': 'jdoe@example.com',
  'user[password]': '',
  'user[companyID]': 'd6633033-7791-479b-8287-66b5d41ef798',
  'user[updatedAt]': '2019-03-16T17:51:05.245Z',
  'user[createdAt]': '2019-03-16T16:53:32.018Z',
  'user[__v]': '0' }

我遇到的问题是,我试图通过一条路由访问req.body.user.email,并且当我console.log记录发布请求的req.body时,会得到上面的输出。

编辑

这是将数据分配给req.user的原因,如果我此时执行console.log,它将显示一个普通的JSON对象,从理论上讲,它可以使用点符号。

request.get('/authorize', options, (error, response, body) => {
      if (error) { return res.status(500).send('Error')}
      if (body == 'Unauthorized') return res.status(400).json({success: false, message: 'Looks like your session has expired. Please log back in to continue.'});
      let result = JSON.parse(body);
      if(result.user.role == role || role == 'all') {
        req.user = result.user;
        next();
      } else {
        return res.status(403).send("You don't have permissions to access this page.");
      }
    });

编辑2

router.get('/authorize', 
  sessions.authorize,
  (req, res) => {
  let user = req.user;
  user.password = '';
  res.json({success: true, user});
});

sessions.authorize返回护照jwt用户

0 个答案:

没有答案
相关问题