sending/receiving HTML forms

Learning about sending/receiving HTML forms.

I rarely write forms nowadays but it's useful skill to have.

Express side

Created simple Express application, how could I receive form fields in it?

Well, it's not straightforward, I had to use body parser


const express = require('express')
const bodyParser = require('body-parser')
const app = express();

app.use(express.json())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}));

app.post('/', (req, res) => {
	console.log(req.body);
	res.send('OKEJ!')
});
//...

Which always seemed strange for me. Few years ago I used Express and I thought maybe in 2023 this could be more simple. I mean, ofc it's few lines of code on beginning of project, but still. Too low level. I kind of expect that such basic thing would work outof the box.

HTML side

Right now I'm sending this form via HTML but what if I wanted to send via fetch?

Well I had problem with sending as application/x-www-form-urlencoded or multipart/formdata, so I sent this as a JSON:


const form = document.querySelector('form');
form.addEventListener('submit', async function(e) {
  const formData = new FormData(this);
  const o = Object.fromEntries(formData.entries());
  e.preventDefault();
  const response = await fetch(e.target.action, {
    method: 'POST',
    body: JSON.stringify(o),
    headers: {
      'Content-Type': 'application/json',
      // 'Content-Type': 'application/x-www-form-urlencoded',
      // 'Content-Type': 'multipart/formdata',
      },
  });
  console.log("RESPONSE", await response.text());
});

So I finally manage to send form via fetch and receive it in Express and send back response! Yey!

Comments

Popular posts from this blog

Communication skills in a team.