Home > Mobile >  Undefined body from post request in nodejs
Undefined body from post request in nodejs

Time:10-19

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>

CodePudding user response:

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.

CodePudding user response:

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())
  • Related