在我的第一个 Node 项目中 Express/Express-resource使用库和Jade用于模板。
根据 docs生成默认映射。其中我们可以发现:
PUT /forums/:forum -> update
但是,我没有看到提交值的简单方法。
如何提交创建/更新?
Jade 表单可以很容易地创建,body parser 也可以,但是如何提交这个表单呢?请注意,express-resource 定义了 PUT 方法(不是 POST)。
最佳答案
来自Express guide :
When using methods such as PUT with a form, we can utilize a hidden input named _method, which can be used to alter the HTTP method. To do so we first need the methodOverride middleware, which should be placed below bodyParser so that it can utilize it’s req.body containing the form values.
所以:
app.use(express.bodyParser());
app.use(express.methodOverride());
在你的表单中:
<input type="hidden" name="_method" value="put">
更新:据我了解提问者的新评论,nrph 想要一种使用 ajax 以 PUT
方法提交表单的方法。这是一个使用 jQuery 的解决方案:
// Use this submit handler for all forms in document
$(document).on('submit', 'form', function(e) {
// Form being submitted
var form = e.currentTarget;
// Issue an ajax request
$.ajax({
url: form.action, // the forms 'action' attribute
type: 'PUT', // use 'PUT' (not supported in all browsers)
// Alt. the 'method' attribute (form.method)
data: $(form).serialize(), // Serialize the form's fields and values
success: function() {},
error: function() {}
});
// Prevent the browser from submitting the form
e.preventDefault();
});
关于forms - 用 express 提交表格的首选方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9739144/