[英]EJS: Trying to use PATCH method with html form
I have just started learning Node.js.刚开始学习Node.js。
I have this following code where I need to submit the form using patch
method to update an existing record.我有以下代码,我需要使用
patch
方法提交表单以更新现有记录。
Language/Edit.ejs语言/Edit.ejs
<form action="//localhost:3000/languages/6343eb83340e657a0321a9cc" method="post">
...
<div class="boxFooter grid gap-2">
<input type="hidden" name="_method" value="patch">
<button type="submit">Update</button>
</div>
</form>
Router路由器
...
Router.patch('languages/:id', validations, update);
...
Controller Controller
import Model from '#Models/Language.js';
...
const update = async (req, res) => {
try {
const item = await Model.findByIdAndUpdate(req.params.id, {
title: req.body.title,
description: req.body.description,
status: req.body.status,
}, {
new: true,
runValidators: true
});
res.send(item);
} catch (error) {
return res.status(400).json('Sorry, we have an error.');
}
};
But, I am getting this error always但是,我总是收到这个错误
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /languages/6343eb83340e657a0321a9cc</pre>
</body>
</html>
I have also tried to use method="patch"
instead of method="post"
.我还尝试使用
method="patch"
而不是method="post"
。 But, the outcome is still the same.但是,结果还是一样。
However, I tried to run this url with postman and it worked flawlessly.然而,我尝试用 postman 运行这个 url 并且它运行完美。
Here is the peace of code that solved my problem.这是解决我的问题的和平代码。 However, I am not sure whether this is the right way or not.
但是,我不确定这是否是正确的方法。
What I did was that I changed the method
to patch
and submitted the form with ajax.我所做的是,我改变了打
patch
的method
并提交了带有ajax的表单。
Here is my code:这是我的代码:
<form action="//localhost:3000/languages/6343eb83340e657a0321a9cc" method="patch">
...
<div class="boxFooter grid gap-2">
<button type="submit">Update</button>
</div>
</form>
<script type="text/javascript">
...
ajaxRequest({
...
type: $('form').attr('method'),
...
})
</script>
...
const ajaxRequest = (params) => {
return $.ajax($.extend(true, {
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: 'POST',
url: '',
data: {},
cache: false,
beforeSend: () => {},
success: (response) => {},
complete: (response) => {}
}, params));
};
...
Is this the right way..?这是正确的方法..?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.