【问题标题】:How to get res json value in Express.js如何在 Express.js 中获取 res json 值
【发布时间】:2020-05-10 03:10:29
【问题描述】:

我是 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 中打印购物车代码,但它没有打印任何内容并引发异常。

【问题讨论】:

    标签: jquery node.js express sap-conversational-ai


    【解决方案1】:

    首先,您尝试调用一个返回 Promise 的函数,它是异步的,并希望它表现得好像它是同步的,但这是行不通的:

    // this won't work
    const response = getCartCode(res)
    
    function getCartCode(res) {
      return createCart().then(function(result) {
        return {...}
      });
    }
    

    如果你想像现在这样使用getCartCode,你必须使用async/await之类的东西,就像这样:

    app.post('/addToCart', function(req, res) {
      async function handleAddToCart() {
        // i suggest you use something like the `lodash.get`
        // function to safely access `conversation.memory.cart`
        // if one of these attributes is `undefined`, your `/addToCart`
        // controller will throw an error
        const cart = req.body.conversation.memory.cart
    
        // or, using `lodash.get`
        // const cart = _.get(req, 'body.conversation.memory.cart', null)
    
        if (!cart) {
          const response = await getCartCode().catch(err => err)
          // do whatever you need to do, or just end the response
          // and also make sure you check if `response` is an error
          res.status(200).json(response)
          return
        }
        // don't forget to handle the `else` case so that your
        // request is not hanging
        res.status(...).json(...)
      }
      handleAddToCart()
    })
    
    function getCartCode() {
      return createCart()
        .then(function(result) {
          return { conversation: { memory: { cart: result } } }
        })
        .catch(function(err) {
          console.error('productApi::createCart error:', err);
          throw err
        })
    }
    

    其次,不要将res 传递给createCart 函数。相反,从createCart 函数获取您需要的数据并在/addToCart 控制器中调用res.json

    你必须如何处理这个问题:

    app.post('/addToCart', function(req, res) {
      const cart = req.body.conversation.memory.cart
    
      if (!cart) {
        getCartCode()
          .then(function (result) {
            res.json(result)
          })    
          .catch(/* handle errors appropriately */)
         return;
      }
      // return whatever is appropriate in the `else` case
      res.status(...).json(...);
    })
    
    function getCartCode() {
      return createCart()
        .then(function(result) {
          return { conversation: { memory: { cart: result } } }
        })
        .catch(function(err) {
          console.error('productApi::createCart error:', err);
          throw err
        })
    }
    

    【讨论】:

      【解决方案2】:

      res 是一个写流。所以res.jsonres.send 将终止流并将响应返回给客户端。您只想从 getCardCode 函数返回 JSON。所以不必将res 发送到getCardCode,只需在控制器中返回Promiseawait

      app.post('/addToCart', async function (req, res) {
        console.log('[POST] /addToCart');
      
        var cart = req.body.conversation.memory['cart'];
        let response = {}
        if (!cart) {
          response = await getCartCode();
          console.log("******* Result ************ : " + response.conversation.memory['cart']); // Giving undefined exception here
        }
        res.json(response); // terminating the writestream with the response.
      });
      

      这里只返回 JSON:

      function getCartCode() {
        return createCart()
          .then(function (result) {
            return {
              conversation: {
                memory: {
                  'cart': result,
                }
              }
            };
          })
          .catch(function (err) {
            console.error('productApi::createCart error: ', err);
          });
      }
      

      注意:如果createCart 返回一个错误,那么response.conversation.memory['cart'] 这一行将抛出一个找不到未定义异常的对话。所以你需要在catch 块中处理它。要么抛出异常,要么返回 JSON,或者您可以为 response 变量添加空检查。

      【讨论】:

        猜你喜欢
        • 2015-09-19
        • 2013-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-02
        • 1970-01-01
        • 2013-07-26
        • 1970-01-01
        相关资源
        最近更新 更多