首页 > 解决方案 > 试图用 PUT 覆盖 POST 方法,但方法覆盖不起作用

问题描述

我正在使用 nodejs,并且我已经安装了方法覆盖作为我的包的一部分。

我有一个表格用来更新我的 mongoDB 中的一本书。bookSchema 如下:

const bookSchema=new mongoose.Schema({
title: {type: String, required: true},
description: {type: String},
publishDate: {type: Date, required: true },
pageCount: {type: Number, required: true},
createdAt: {type: Date, required: true, default: Date.now},
coverImage: {type: Buffer, required: true},
coverImageType: {type: String, required: true},
author: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'Author'}})

我有以下带有表单的 HTML 表单:

<h2>Edit Book</h2>
<form action="/books/<%= book.id %>?=_method=PUT" method="POST" >  
    <%- include('_form_fields')%>  
    <a href="/books/<%= book.id %>">Cancel</a>
    <button type="submit">Update</button>
</form>

表单字段保存在名为 _form_fields.ejs 的单独 ejs 文件中。问题是,当我单击上面表单上的“更新”按钮时,我在浏览器中收到以下错误:

" Cannot POST /books/6027aadff143f81a30841721"

但我希望错误是

" Cannot PUT /books/6027aadff143f81a30841721"

因为我使用了方法覆盖。结果,该按钮没有选择我的路线中定义的“放置动作”。

我已经在这个项目的另一个表单上成功实现了方法覆盖,但这不起作用。

有关其他信息,我在下面包含了我的 router.put 代码:

router.put('/:id',async (req, res)=>{

let book
console.log("Clicked")

try{
    book=await Book.findById(req.params.id)
    book.title=req.body.title
    book.author=req.body.author
    book.publishDate=new Date(req.body.publishDate)
    book.pageCount=req.body.pageCount
    book.description=req.body.description
    if (req.body.coverImage!=null && req.body.coverImage!==""){
        saveCover(book, req.body.coverImage)
    }
    await book.save()
    
    res.redirect(`/books/${book.id}`)
}catch(err){
    
    if(book!=null){
        
        renderEditPage(res, book, true)
    } else{
        res.redirect('/')}}})

标签: htmlnode.jsoverriding

解决方案


我终于发现我的语法是错误的:

?=_method=PUT"本来应该?_method=PUT"

    <h2>Edit Book</h2>
<form action="/books/<%= book.id %>?_method=PUT" method="POST" >  
    <%- include('_form_fields')%>  
    <a href="/books/<%= book.id %>">Cancel</a>
    <button type="submit">Update</button>
</form>

经验教训:总是检查你的代码是否有错别字


推荐阅读