Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

323
Vistas
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)
        })
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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)
})
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda