What is the preferred way to submit a form using express?

In my first project, Node Express / Express-resource and Jade for templates.

According to docs , default mappings are displayed. Among them you can find:

PUT /forums/:forum -> update 

However, I do not see a simple way of representing values.

How to send creation / update?

A Jade form can be created easily with the body parser, but how to submit this form? Note that the express resource defines the PUT method (not POST).

+4
source share
1 answer

In the Express Guide :

When using methods such as PUT with a form, we can use a hidden input called _method, which you can use to modify the HTTP method. To do this, we first need the middleware methodOverride, which must be placed below the bodyParser so that it can use its req.body containing the form values.

So:

 app.use(express.bodyParser()); app.use(express.methodOverride()); 

And in your form:

 <input type="hidden" name="_method" value="put"> 

Update:. As I understand the new comments from asker, nrph wants to submit the form using the PUT method using ajax. Here is a solution using 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 fields and values success: function() {}, error: function() {} }); // Prevent the browser from submitting the form e.preventDefault(); }); 
+6
source

Source: https://habr.com/ru/post/1401826/


All Articles