如何在nodejs的URL中使用ajax接收客户端发送的variables值?

我有一个URL ,我想sendserverajax为了delete产品基于id 。 我怎样才能receive NodeJS ,就像我在PHP api这样做:

 $sProductId = $_GET['id']; 

这是来自ajax调用的URL:

 var sUrl = "/delete-product" + sProductId; 

这是我的server.js

 app.post('/delete-product' ???, upload.none(), (req, res) => { global.sUpdateProductImagePath = req.file.path.split("public/")[req.file.path.split("public").length - 1] user.deleteProduct(req.body, (err, jResult) => { if (err) { console.log(jResult) return res.send(jResult) } console.log(jResult) return res.send(jResult) }) }) 

和我的user.js:

 user.deleteProduct = (jProductData, fCallback) => { global.db.collection('products').deleteOne({ "_id": "" }, (err, jResult) => { if (err) { var jError = { "status": "error", "message": "ERROR -> deleteProduct -> user.js -> 001" } return fCallback(false, jError) } var jOk = { "status": "ok", "message": "user.js -> product deleted -> 000" } console.log(jResult) return fCallback(false, jOk) }) } 

你可以这样做,如果你想在path参数id

 app.post('/delete-product/:id', upload.none(), (req, res) => {var id= req.params.id; // this id is from path params 

您也可以在search查询中发送id / delete-product?id = yourid

  app.post('/delete-product', upload.none(), (req, res) => {var id= req.query.id; 

传递参数从客户端发送到服务器的方式是get方法。 该ID是url的一部分。

所以,在服务器上,你应该改变post获取并添加/:idproduct来接收它。

另外,而不是req.body,你应该改变为req.params .:

例如:

app.get('/ delete-product /:idproduct',(req,res)=> {

  //global.sUpdateProductImagePath = req.file.path.split("public/")[req.file.path.split("public").length - 1] //req.body = req.params.idproduct user.deleteProduct(req.params.idproduct, (err, jResult) => { if (err) { console.log(jResult) return res.send(jResult) } console.log(jResult) return res.send(jResult) }) })