• Edit


    要使用Put之前,在index.js中require method-overrise
    const methodOverride = require('method-override')
    app.use(methodOverride('_method'))
     
    <form action="/products/<%=product._id%>?_method=PUT" method="POST">
     
    index.js 

    const methodOverride = require('method-override')
      app.use(methodOverride('_method'))
    app.get('/products/:id/edit', async (req, res) => {
        const { id } = req.params;
        const product = await Product.findById(id);
        res.render('products/edit', { product })
    })
    
    app.put('/products/:id', async (req, res) => {
        const { id } = req.params;
        const product = await Product.findByIdAndUpdate(id, req.body, { runValidators: true, new: true });
        res.redirect(`/products/${product._id}`);
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Edit product</title>
    </head>
    
    <body>
        <h1>Edit a product </h1>
    
        <form action="/products/<%=product._id%>?_method=PUT" method="POST">
            <label for="name">Name</label>
            <input type="text" name="name" id="name" placeholder="product name" value="<%=product.name%>">
            <label for="price">price</label>
            <input type="number" name="price" id="price" placeholder="price" value="<%=product.price%>">
            <label for="category">Select category</label>
            <select name="category" id="category">
                <option value="fruit">fruit</option>
                <option value="vegetable">vegetable</option>
                <option value="dairy">dairy</option>
            </select>
            <button>Submit</button>
            <!-- Submit按钮一旦点击,提交页面/products, post,跟index.js里面的app.post('/products',。。。)连接着 -->
        </form>
    
        <a href="/products/<%=product._id%>">Cancel</a>.   //cancel回到待编辑页面

    </body> </html>

  • 相关阅读:
    freemarker报错之五
    freemarker处理空值
    freemarker报错之四
    freemarker之include指令
    freemarker之list
    freemarker报错之三
    freemarker中的if...elseif...else语句
    freemarker获取封装类中对象的属性
    单块读和多块读操作汇总
    freemarker报错之二
  • 原文地址:https://www.cnblogs.com/LilyLiya/p/14397391.html
Copyright © 2020-2023  润新知