Kavinkumar . N
Kavinkumar . N

Reputation: 321

bodyParser returns empty object for POST REQUEST

Here is my js File of front-end(REACT-NATIVE)

Booking.js

fetch('http://192.168.64.1:3000/updateOrdersInsert', {
           method: 'POST',
           body: product,
           headers: {
                  Accept: 'application/json',
                  'Content-Type': 'application/json',
                  }
     })
     .then( response => response.json())
     .then(data => {
        console.log(`Booking Component Updated ${data}`);
        this.props.navigation.navigate('Orders',{product:this.state.product})
        return;
     })
     .catch(err => {
        console.log(`ERROR THROWN AT BOOKINGS  ${err}`)
     })

Here is my back-end(EXPRESS)

Server.js

const bodyParser = require('body-parser');
const express =require('express');
const mysql = require('mysql'); 

const app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

const con = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '***',
    database : 'myntra'
 });

 con.connect(function(err){
    if(err)
    throw err;
    console.log("connected");
})


app.post('/updateOrdersInsert',(req,res) => {
    console.log(req.body); //returns empty Object '{}'
    console.log(`USER => ${req.body}`);
    for(key in req.body){
        console.log(`Key => ${key} value => ${req.body[key]}`);
    }
    res.end();
})

app.listen(3000,() => {
    console.log('Node Server Listening at 3000 http://localhost:3000');
})

When I try to make POST Request using fetch call to express app, I am trying to object in body,,,,

But in express app it prints empty object? :(
I don't know why?

Upvotes: 0

Views: 96

Answers (1)

Marcel
Marcel

Reputation: 183

Maybe you are missing the stringify of the body object?

fetch('http://192.168.64.1:3000/updateOrdersInsert', {
    method: 'POST',
    // stringify content
    body: JSON.stringify(product),
    headers: {
     Accept: 'application/json',
     'Content-Type': 'application/json',
    }
})

Upvotes: 1

Related Questions