Making HTTP Requests using Html Forms

Code Your Thoughts
2 min readJun 9, 2023

--

Html forms are mostly used when we want to take some data from user.

For example, during student registration we would want user to enter details like name, class and uid. And then this data is sent back to the backend and then is saved in the database.

Html Forms only support two types of Http requests. Get and Post.

But to make Put, Delete and Patch requests we would need NodeJs module called ‘method-override’.

Html Forms to make :

  1. ‘Get’ Request

By default, forms in html make get requests.

<form action='/home' method='GET'>
<input type='submit'>
</form>

2. ‘Post’ Request

To make post requests we just have to set ‘method’ attribute of <form> to ‘POST’.

<form action='/home' method='POST'>
<input type='submit'>
</form>

Now, To make PUT, DELETE and PATCH requests using html forms, we need a NodeJs module called ‘method-override’

Steps to use method-override :

a. Install method-override module

npm install method-override

b. Now require the modules express and method-override and setup basic express app.

const express = require('express');
const methodOverride = require('method-override');

const app = express();

// configure methodOverride

app.get('/', (req, res) => {
res.send('Get Home page');
})

app.post('/', (req, res) => {
res.send('Post Home page');
})

app.put('/', (req, res) => {
res.send('Put Home page');
})

app.delete('/', (req, res) => {
res.send('Delete Home page');
})

app.patch('/', (req, res) => {
res.send('Patch Home page');
})

app.listen(3000, () => console.log('listening on port 3000...'));

after const app = express();

c. Create a middleware function to use method-override.

app.use(methodOverride('_method'));

here’_method’ is the query string that we have to provide to the url in ‘action’ attribute of forms. And the value of this query ‘_method’ will be the Http request verbs that we want to use.

Note: ‘_method’ can be named anything.

3. Making ‘Put’, ‘Delete’ and ‘Patch’ Requests

Just set query string _method to PUT or DELETE or PATCH to the URL in the action attribute of Form.

And set method attribute to ‘POST’.

e.g.

using put :

<form action='/home?_method=PUT' method='POST'>
<input type='submit'>
</form>

And this is how we make all types of http request using forms. Alternatively we could use AJAX to make different requests, but that would be topic for my next article.

Please give a clap to this article if you found it informative and do follow me for my further writings.

--

--

Code Your Thoughts

Exploring tech, programming, and coding. Unraveling trends, sharing insights, and empowering enthusiasts. https://linkedin.com/in/raj-ritik