Skip to content
Advertisement

formData in React, getting null when I send formdata to backend Express

When I send data from the frontend I receive null in the backend. I am sending 2 string data URLs and dates so I don’t think that I need to use extra middleware for receiving the values.

Frontend:

    const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault()
        const today = new Date();
        const date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
        const formData = new FormData();
        formData.append('url', url);
        formData.append('date', date);
        console.log(url, date);

        fetch('http://localhost:5000/shortUrls', {
        method: 'post',
        body: formData
    })
        .then(response => response.json())
        .then(data => {
            if (data.insertedId) {
                alert('Link Added')
                setLoadings(true)
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });

    }

Backend:

// middleware
const app = express();
app.use(cors())
app.use(express.json())

app.post('/shortUrls', async (req, res) => {
            const uniqueUrl = shortId({ url: req.body.url })
            console.log(req);
            const details = {
                short: uniqueUrl,
                full: req.body.url,
                clicks: 0,
                date: req.body.date,
            }
            const result = await AffiliateLinksCollection.insertOne(details)
            res.json(result)
        })

Advertisement

Answer

it’s empty because on the server you have a json parser, but you’re sending a multipart/form-data request, and there is no parser to process it.

as you’re not uploading a file, the easiest way would be to send a json request:

e.preventDefault()
const today = new Date();
const date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();

// use object
const formData = {url, date};
console.log(url, date);

// post json
fetch('http://localhost:5000/shortUrls', {
  method: 'post',
  headers: {
      'Content-Type': 'application/json'
  },
  body: JSON.stringify(formData)
})

if you want to use FormData, you need to include parser on the server. usually, this is multer, but as you’re not uploading a file, use body-parser

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

however, as FormData is sending data as multipart/form-data, bodyParser cannot parse it, so you need to turn it into URL-encoded string with URLSearchParams

fetch('http://localhost:5000/shortUrls', {
    method: 'post',
    body: new URLSearchParams(formData)
})
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement