skip to Main Content

I am working with Nodejs and using expressjs,Right now i am trying to use "body-parser" with "router" but right now i am getting following error [object object],How can i solve this ? Here is my "api.router.js" file

const express = require('express');
const apiController = require('../controllers/api.controller');
const router = express.Router();
var bodyParser = require('body-parser')
// Endpoint for creating a new record
router.post('/new', apiController.addUser);
module.exports = router;

And here is my "api.controller.js"

const User = require('../models/user.model');
const addUser = async (req, res) => {
const { firstName, lastName, age } = req.body;
  console.log(req.body);
  ...
}

3

Answers


  1. remove the following line from your code:

    var bodyParser = require('body-parser');
    

    And instead, add the following code to your api.router.js file, before defining the routes:

    router.use(express.json());
    router.use(express.urlencoded({ extended: true }));
    
    Login or Signup to reply.
  2. There are two types of usage explained by the author

    Express/Connect top-level generic
    And
    Express route-specific

    You can use any one of them or conditionally use based on your requirement

    Login or Signup to reply.
  3. You can use app.use(bodyParser.json()); or app.use(express.json());

    const express = require("express");
    const app = express();
    var bodyParser = require('body-parser')
    const helloworld_route = require("./routes/helloworld");
    
    const port = process.env.PORT || 2000;
    
    app.use(bodyParser.json());
    
    app.use("/", helloworld_route);
    
    app.listen(port, () => {
     console.log(`Listening on ${port}`);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search