调用PUT以从EJS进行表达

问题描述 投票:0回答:1

我正在尝试从EJS形式调用在expressjs中创建的一个宁静的api。

我尝试在google和stackoverflow上进行查找,并尝试了许多不同的方法。

orders.ejs:

 <ul class="orders">
<% for(var i=0; i<orders.length; i++) {%>
  <ul class="order">
    <p> coffee_id <span><%= orders[i].name %></span>
        amount: <span><%= orders[i].amount %></span>
        quantity <span><%= orders[i].quantity %></span>  </p>
  </ul>
<% } %>
</ul>



<div>
    <form action="/orders" method="POST" action="orders/?_method=PUT">
      <input type="text" placeholder="username" name="username">
      <input type="text" placeholder="coffee name" name="name">
      <input type="number" placeholder="amount" name="amount">
      <input type="number" placeholder="quantity" name="quantity">
      <button type="submit" id="order" >Submit</button>
    </form>
  </div>

nodejs.app.js:

app.post('/orders', (req, res) => {  // falta o EJS
  db.collection('orders').save(req.body, (err, result) => {
    if (err) return console.log(err)
      console.log(req.body);
    res.render('orders.ejs', {
      put: true
  });
  })
})

app.put('/orders/:coffeeid/:quantity', function(req, res) { ...
}

此代码可以很好地单独使用正确的参数从Postman调用它们,但是在提交EJS表单时我需要同时调用它们。

app.get('/orders/:coffeeid',function(req, res) { 
  db.collection('orders').find({_id:req.params.coffeeid}).toArray, function(error,result){
      if(!error && result && quantity){
            return res.render('orders.ejs',{orders: result, coffeeid:result.coffeeid, quantity:'7'});  // <-- pass coffeeid to view
      }
  }
});

我还需要从表格中读取数量并检查PUT中的库存,因此现在我将其固定为'7'个单位,但现在无法获取/订单

order view

node.js express ejs
1个回答
0
投票

获取订单的路线:

  app.get('/orders',function(req, res) { 
       // fetch all orders and display it to view 
  });

按coffeeid显示订单的显示编辑页面的路径:

app.get('/orders/:coffeeid',function(req, res) { 
   var coffeeid= req.params.coffeeid;

   db.collection('orders').find({_id:coffeeid}).toArray,function(error,result){
     if(!error && result){
        return res.render('orders.ejs',{orders:result,coffeeid:result.coffeeid, quantity:'7'}); 
      }
    });

});

form:

 <form action="/orders/<%=coffeeid%>" method="POST">

      <input name="_method" type="hidden" value="PUT">
      <input type="text" placeholder="username" name="username">
      <input type="text" placeholder="coffee name" name="name">
      <input type="number" placeholder="amount" name="amount" value="">
      <input type="number" placeholder="quantity" name="quantity" value="<%=quantity%>">

      <button type="submit" id="order" >Submit</button>

   </form>

更新信息路线将是:

app.put('/orders/:coffeeid', function(req, res) { 
   var coffeeid= req.params.coffeeid;
   var quantity= req.body.quantity;

  // save to database 
}
© www.soinside.com 2019 - 2024. All rights reserved.