Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!