如何在nodejs中获取项目的单个id



我有一个删除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"
}
]

您可以通过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
});

您可以使用隐藏的输入

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

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

最新更新