【问题标题】:how to get the individual id of an item in nodejs如何在nodejs中获取项目的单个ID
【发布时间】:2020-06-10 21:53:12
【问题描述】:

我有一个删除 api,它接受我们要删除的项目的 id,每个项目都有其唯一的 id,我如何获取要删除的项目的 id 并将其传递给我的 api

这里是api

    app.post("/delete_product", function (req, res) {
            var data = {
                id: req.session.user_id,
                token: req.session.token,
                product_id: 4
    // you need to pass in the id of the product in data.product_id
            };
           functions.callAPIPost(
                "https:/theurl/delete_product",
                data,
                function (error, result) {
                    var response = result;
                    if (response.status === 400) {
                        console.log('ggg',response)
                        res.render('products', {
                            result: result.data
                        })
                    } else {
                        res.redirect('logout')
                    }
                }

            );
        });

这是我的 ejs

<form method='post'  action='/delete_product'>
       <button><iclass="os-icon os-icon-trash" style='font-size: 16px; display: inline-block; vertical-align: middle; margin-right: 10px; color: #8095A0;'></i><span>Delete</span></button>
</form>

我有一个对象数组,在我遍历它们后在浏览器中显示为项目,它们都有各自的 id,一旦用户单击调用 api 的项目删除按钮,我如何获取 id删除它。

 [
        {
            "id": 3,
            "name": "work dress",
            "description": "take to work dress",
            "price": "2000",
            "created_at": "2020-02-26T20:30:08.000Z"
        },
        {
            "id": 4,
            "name": "movie dress",
            "description": "take to movie dress",
            "price": "2000",
            "created_at": "2020-02-26T20:30:08.000Z"
        },
        {
            "id": 5,
            "name": "home dress",
            "description": "stay at home dress",
            "price": "2000",
            "created_at": "2020-02-26T20:30:08.000Z"
        }
    ]

【问题讨论】:

    标签: javascript arrays node.js express ejs


    【解决方案1】:

    您可以通过 POST URL 传递它,并通过 req.params 访问 NodeJS 中的值。

    在 EJS 中 -

    <form method='post'action='/delete_product/<%= product._id %>?_method=DELETE'>
    

    在 NodeJS 中 -

    app.delete("/delete_product/:id", function (req, res) {
    
        var id_to_delete = req.params.id;
    
        //rest of the code
    });
    

    【讨论】:

      【解决方案2】:

      您可以使用hidden input

      <input type='hidden' name='product_id' value='1' />
      

      然后在你的 api 中你可以在 POST 数据对象中获取它

      【讨论】:

      猜你喜欢
      • 2015-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 2020-11-08
      • 2019-02-17
      • 1970-01-01
      相关资源
      最近更新 更多