发送简单的JSON响应Nodejs

时间:2018-03-29 09:28:36

标签: node.js response httpresponse

我正在尝试向连接到我的api的客户端应用程序发送一个简洁且易于解析的json响应。以前,我已发送此格式的回复:

{
"success": false,
"message": "All Items Fetched",
"cartItems": [
    {
        "_id": "5abca75f43b4c21ec482e96d",
        "title": "Apples",
        "price": 594,
        "quantity": 6,
        "prodId": "5aadb71792f47742d4e3749b",
        "__v": 0
    },
    {
        "_id": "5abca75f43b4c21ec482e96e",
        "title": "Red and Mixed Grapes",
        "price": 645,
        "quantity": 5,
        "prodId": "5aac5dac664a9042a44bf787",
        "__v": 0
    },
    {
        "_id": "5abca76143b4c21ec482e96f",
        "title": "AnanaB",
        "price": 445,
        "quantity": 5,
        "prodId": "5ab1c1a8044a584bdcad6e1d",
        "__v": 0
    }
 ]
}

但是现在,为了简洁起见,我希望以这种方式为每个数组项发送一个响应6 * of Apples

我试过这段代码:

let cart = await Cart.find({});
console.log('Checkout Cart:\t' + cart);

let cartArr = [cart];
console.log('Cart Arr:\t' + cartArr);

for (quantity, title in cart){
    console.log( quantity + 'x of' + title);
}

但它会在for循环中抛出此错误:

SyntaxError: Invalid left-hand side in for-loop
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:599:28)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Module.require (module.js:579:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (D:\Workspace\AdminBootstrap\app.js:24:14)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Function.Module.runMain (module.js:676:10)
[nodemon] app crashed - waiting for file changes before starting...

如何遍历此数组以获得此输出? 感谢。

3 个答案:

答案 0 :(得分:0)

Find返回一个对象数组。

购物车将如下所示

reloader.clear()

答案 1 :(得分:0)

不确定这是否符合您的预期......这就是您可以循环使用的方式......

  

for((obj.cartItems中的数量){
  console.log(obj.cartItems [qty] .quantity +&#39; of&#39; +   obj.cartItems [qty] .title)}

其中* obj是从节点获得的对象响应。

答案 2 :(得分:0)

您需要在循环中使用if (past) {//check if past is not null or undefined document.getElementById('previous').innerHTML = past; else { document.getElementById('previous').innerHTML = ''; } 并使用大括号进行对象解构才能工作:

of

当然,for (const {quantity, title} of cart) { console.log('%s of %s', quantity, title); } 包含JSON中显示的数组为cart