forms - 用 express 提交表格的首选方式是什么?

标签 forms node.js express

在我的第一个 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/

相关文章:

python - Circleci 与 gcloud sdk UnicodeDecodeError

javascript - 使用客户端和服务器在两个单独的文件夹中将 Node 应用程序部署到 heroku

Javascript 如果为空则不起作用?

php - 将 Canvas 图像和表单数据发送到服务器以命名为 png

php - 在新页面上显示当前表单提交的结果

node.js - Nodejs express ,Heroku CORS

node.js - Mongoose 分页 : Overflow sort stage buffered data usage?

javascript - div id 中的连字符导致 javascript 错误

javascript - 如何在 Discord 中创建一个接受用户输入的弹出窗口?

javascript - Web Worker 和 Worker Threads 有什么区别?