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

114
Vistas
Undefined body from post request in nodejs

I created the API in node js and in the POST method getting the body as undefined. How can I get the value that is passed using the fetch?

code for NodeJs-------------------------------------------

const express=require('express');
const app=express()
const port=3000
const fs=require('fs');


app.get('/',(req,res)=>{
    res.send('hello world!');
});

app.get('/movies',(req,res)=>{
    fs.readFile(__dirname+'/movies.json','utf-8',(err,data)=>{
        res.send(data);
    });
});

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

app.listen(port,()=>{
    console.log(`app listening at http://localhost:${port}`)
});

code for HTML-------------------------

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <form onsubmit="submitted(event)">
        <input id="field" type="text" required="true">
        <button type="submit">save</button>
    </form>
</body>
<script>
    function submitted(e){
        e.preventDefault();
        const value=document.getElementById('field').value;
        await fetch('http://localhost:3000/movies',{
            method:'POST',
            body:{value},
            mode:'no-cors',
            headers:{
                "Content-Type" : "application/json",
                'Access-Control-Allow-Origin':'*'
            }
        });
    }
</script>
</html>
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You need to use a middleware to parse the body correctly. It looks like you're sending JSON, so you'll need the bodyParser middleware provided by express.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Well you have got 2 problems:

1 Problem:

You need to stringify your body like

  body:JSON.stringify({value})

2 Problem:

In express you need to parse your body. For that express provides .json()

const express=require('express');
const app=express()
const port=3000
const fs=require('fs');

app.use(express.json())
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