如何在Express.js中获取res json值

编程入门 行业动态 更新时间:2024-10-07 21:37:58

<a href=https://www.elefans.com/category/jswz/34/1771448.html style=如何在Express.js中获取res json值"/>

如何在Express.js中获取res json值

我是node.js的新手。我正在尝试做这样的事情-

我创建了一个添加到购物车的API,首先要检查会话购物车是否存在。如果不存在,我将通过getCartCode(res)方法创建新的购物车。

app.post('/addToCart', function(req, res) {
console.log('[POST] /addToCart');

var cart = req.body.conversation.memory['cart'];

if(!cart) {
   const response = getCartCode(res);
   console.log("******* Result ************ : " + response.conversation.memory['cart']); // Giving undefined exception here
}
}

getCartCode-此方法创建购物车并返回我通过res.json返回的代码

function getCartCode(res)  {

return createCart()
  .then(function(result) {
    res.json({
      conversation: {
        memory: {
          'cart': result,
        }
      }
    });

    return result;
  })
  .catch(function(err) {
    console.error('productApi::createCart error: ', err);
  });
 }

现在我想要的是,我想在addToCart API中获得购物车代码作为响应。我正在尝试在console.log中打印购物车代码,但没有打印任何内容并引发异常。

回答如下:

这是您必须处理的方式:

app.post('/addToCart', function(req, res) {
  const cart = req.body.conversation.memory.cart

  if (!cart) {
    getCartCode()
      .then(function (result) {
        res.json({
          conversation: {
            memory: { "cart": result }
          }
        })
      })    
      .catch(/* handle errors appropriately */)
     return;
  }
  // return whatever is appropriate here
  res.status(...).json(...);
})

function getCartCode() {
  return createCart()
    .catch(function(err) {
      console.error('productApi::createCart error:', err);
      throw err
    })
}

更多推荐

如何在Express.js中获取res json值

本文发布于:2024-05-07 09:13:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1755550.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Express   js   res   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!