1

I am trying to send html form data to server via a fetch 'POST' request but at server side I am getting Empty request body. I have already tried different solutions provided on stack overflow but none of them is working at my end. could anyone please help me identify where I am going wrong.

  1. I have the form with id 'signup-form' in my html file

  2. client side JavaScript the code goes like below:

const  myForm = document.getElementById('signup-form')

myForm.addEventListener('submit', (e) => {
    e.preventDefault()
    const myForm = document.getElementById('signup-form')
    const data = new FormData(myForm)
    const option= {
        method: 'POST', 
        headers: {
            'Content-type': 'application/json'
        },
        body:JSON.stringify(data)
    }
    fetch('/login', option).then(
        response => response.json()
    ).then(
        data => console.log(data)
    ).catch(
        error => console.log(error)
    )
})
  1. Server side express js code goes like below
app.use(express.urlencoded({ extended: false}))
app.use(express.json())

app.post('/login', (req, res) => {
    console.log('url is', req.url)
    const info = req.body;
    console.log('info is:', info)
    res.status(201).json({ 'submitted': true })
})

app.listen(3000, () => {
    console.log('listening on port 3000')
})
Mohit Soniwal
  • 13
  • 1
  • 3

1 Answers1

0

With FormData you cannot POST application/json, because that is not on the list of content types supported by a form element.

Instead, write something like

const data = {element1: "value", element2: "value2", ...};
Heiko Theißen
  • 12,807
  • 2
  • 7
  • 31