jpazzajpeg
jpazzajpeg

Reputation: 163

req.body not working on express router post requests

Post request coming in from a React front-end. However, when I try to access req.body in a post request set up under express router it simple logs as [object Object]. Beginner programmer any help much appreciated!!

I'm trying to learn how to modularize my routes in an express.js app but I can't access req.body on POST requests. I've spent hours trying to find a solution with no success.

I 100% have installed body-parser.

My server.js file:

const express = require('express');
const app = express();
const router = express.Router();
const PORT = process.env.PORT || 4000;

const cors = require('cors');
const bcrypt = require('bcryptjs');
const passport = require('passport');
const bodyParser = require('body-parser')

app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json()); //And so on.
app.use(cors());


// ROUTES - Require Routes defined in directory
const productsRoutes = require('./routes/products')

// ROUTES - use routes defined in directory
app.use('/products', productsRoutes);


app.listen(PORT, () => {
  console.log(`listening on PORT ${PORT}`);
})

The routes/products page:

const express = require('express');
const router = express.Router();
// const bodyParser = require('body-parser')

router.get('/', ( req, res ) => {
 res.status(200).json({message: 'Connected to the products!' });
})

router.post('/', ( req, res ) => {
  console.log(`req.body ${req.body}`);
  res.status(200).json({message: 'Connected products products!' });
})

module.exports = router;

REACT front-end:

  componentDidMount(){

     axios.post('http://localhost:4000/products', {
       headers: {searchText: this.state.searchText}
     })
     .then( res => {
       console.log('GOT PRODUCTS', res.data);
       this.setState({ products: res.data})
     })
     .then(json => {
        this.setState({ loading: true });
        setTimeout(() => {
           this.setState({ done: true });
        }, 1000);
     });
  }, 1200);
  }

If someone knows how I can access the req.body in a router.post('/---') request I would be very grateful

Upvotes: 1

Views: 2106

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138537

it simple logs as [object Object] ...

Thats what happens if you try to concat an object to a string:

   console.log("you see: " + {});

Thats because {}.toString() returns the string "[Object object]". Thats not really useful though. Instead you could judt pass the object on its own to console.log, that way it gets shown more elgantly:

  console.log("result :", { it: "works" });

(And if you connect a debugger you can even interact with it)

Upvotes: 0

Related Questions