html - 试图用 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('/')}}})
解决方案
我终于发现我的语法是错误的:
?=_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>
经验教训:总是检查你的代码是否有错别字
推荐阅读
- python - Python对列表中的值进行子集化
- jestjs - 开玩笑地嘲笑 axios 不是嘲笑
- rabbitmq - 重新排队过期消息的 Rabbitmq 问题
- angular - 包含 cordova.js 时,Angular Cordova 应用程序变为空白
- linux - Python3:无法在 Stratodesk/Notouch OS 上安装 evdev --> 无法执行“arm-linux-gnueabihf-gcc”:没有这样的文件或目录
- python - 从端点获取数据并将其存储在 csv 中
- java - org.gradle.tooling.BuildException: 处理资源失败,详见上面的 aapt 输出
- c++ - 我们如何将字符串转换为数字并可逆?
- python - 我无法运行由 cx_Freeze 构建的电子邮件程序
- android - 作为响应获取单个对象我如何根据我的要求进行解析