我刚刚开始学习Node.js.
我有以下代码,需要使用patch
方法提交表单以更新现有记录。
语言/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.patch('languages/:id', validations, update);
...
控制器
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.');
}
};
但是,我得到这个错误总是
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /languages/6343eb83340e657a0321a9cc</pre>
</body>
</html>
我还尝试使用method="patch"
而不是method="post"
。但是,结果仍然是一样的。
然而,我试着用邮递员运行这个url,它运行得很完美。
这是解决我问题的代码。不过,我不知道这是否正确。
我所做的是将method
更改为patch
,并使用ajax提交表单。
这是我的代码:
<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));
};
...
这是正确的方式吗。。?