Missing data: Node JS fails to recognize req.body

I've looked through various posts and I'm feeling quite lost with this issue.

When I run console.log(req), the output is as follows:

ServerResponse {
  ...
  req: 
   IncomingMessage {
    ...
     url: '/my-endpoint',
     method: 'POST',
     statusCode: null,
     statusMessage: null,
     ...
     body: { foo: 'bar' },
     _body: true,
     ...
     route: Route { path: '/my-endpoint', stack: [Object], methods: [Object] } },
  ...

Everything seems fine, so naturally, I thought console.log(req.body) would return { foo: 'bar' } in the console...however, it returns undefined

After some investigation, I suspect there might be an issue in my app.js file related to body-parser, but I have already included all the necessary configurations

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var http = require('http');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//Home Page Rendering
var index = require('./routes/index');
app.use('/', index);

// All other routes are kept in the `routes` module
require('./routes')(app);

module.exports = app;

routes.js

module.exports = function routing(app) {
  var apiClient = require('./services/apiClient');

  app.post('/get-device-info', function(err, req, res){
    console.log("/get-device-info routes");
    apiClient(req, res);
  });
};

apiClient.js

module.exports = function callApi(req, res){
  console.log(req);
  console.log(req.body)
};

index.js

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

Here's what I've attempted:

app.use(express.bodyParser());

Ensuring that the incoming request explicitly declares application/json

Trying different ways to declare body parser.json

Adding a config function

Answer №1

The issue you're facing is that Express does not utilize error first callbacks for its route handlers. The code snippet provided will not work because the handler for app.post does not follow the required signature of (req, res) => {}. In this code, err is being used as req, req as res, and res as next.

// routes.js
module.exports = function routing(app) {
  var apiClient = require('./services/apiClient');

  app.post('/get-device-info', function(err, req, res){
    console.log("/get-device-info routes");

    // Assuming the request is correct 
    // the value of body will be the request body  
    console.log(res.body)

    apiClient(req, res);
  });
};`

Express offers different route callback signatures to use:

  • (req, res) => {} - Basic route handling that only requires access to the request and response objects.
  • (req, res, next) => {} - Middleware callback that includes the next parameter to move on to the next matching route.
  • (err, req, res, next) => {} - Error handling route callback which serves as a catch-all for errors within Express Router Middleware or App structures. It triggers when next(err) is called within a Route or Middleware function.

To fix the issue, update the route definition like this:

app.post('/get-device-info', (req, res) => {
  apiClient(req, res)
})

An alternative approach could be:

module.exports = app => {
  let apiClient = require('./services/apiClient')

  app.post('/get-device-info', apiClient)
}

Answer №2

Give this method a try as it has worked successfully for me.

To ensure everything runs smoothly, start by initializing app and then the bodyParser. Remember that bodyParser is utilized within app:

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

Next, include these lines of code below:

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to utilize href alongside the urlRouterProvider?

Within my angularjs application, I opted to switch from using ngRoute (routeProvider) to ui.router (urlRouterProvider) module and stateProvider for transitioning between different states in the app. However, I recently discovered that ui-router only suppo ...

Blip Scripts: Converting JSON to JavaScript - Dealing with Undefined Arrays

I am currently working on a project to develop a bot on Blip. There are certain parts where I need to send a request to an API and then use a JavaScript script to extract elements from the JSON response. The JSON response I received from the API is stored ...

Analyzing the current time against a user-inputted time using Javascript

Looking at this html and javascript code, the goal is to compare an input time with the current time. If the input time is less than 2 hours, "Less time" should be displayed in the label; if it's more than 2 hours, then "sufficient time" should appear ...

Accessing complex nested relationships with bookshelf's withRelated()

I have a User entity that has a relationship of belongToMany with Group. Each Group can also establish a relationship of belongToMany with ReviewQueueStatus, and each ReviewQueueStatus can have multiple instances of ReviewQueues, which in turn is connected ...

Typing should be positioned on either side of the declaration

When I define the type MyType, it looks like this: export type MyType = { ID: string, Name?: string }; Now, I have the option to declare a variable named myVar using three slightly different syntaxes: By placing MyType next to the variable ...

I'm attempting to render HTML emails in ReactJS

I have been attempting to display an HTML page in React JS, but I am not achieving the same appearance. Here is the code snippet I used in React JS: <div dangerouslySetInnerHTML={{ __html: data }}/> When executed in regular HTML, the page looks lik ...

Guide on clearing the value of the first textarea and transferring it to the second textarea using JavaScript

I have encountered an issue where the first textarea value is being copied into the second textarea because I am using the same id for the 'add more' functionality. Below is the code snippet: <div id="divShortAnswerOption_Templated"> & ...

Managing various swipe interactions using HTML and JavaScript/jQuery

I'm in the process of creating a mobile multiplayer game using HTML5 and Javascript. The jQuery Plugin "touchwipe" is utilized to manage swipe events in various divs like this: $('#play1').touchwipe({ wipeLeft: function(){ if ...

Troubleshooting VueJs and vue-i18n issues

Currently, I am utilizing the Webpack CLI Template. As a next step, I proceed to install using the command npm install --save vue-i18n Within my main.js file, I undertake the necessary importation and configuration by setting the locale to "en" import ...

Transition smoothly between sections using fullPage.js with clipping path effects

I am looking to create a unique clipping animation utilizing SVG clipping path. The animation should hide the first section while revealing the second section in a smooth transition using fullPage.js. This idea is somewhat similar to the question discusse ...

CrossBrowser - Obtain CSS color information

I'm attempting to retrieve the background color of an element: var bgcolor = $('.myclass').first().css('background-color') and then convert it to hex function rgbhex(color) { return "#" + $.map(color.match(/\b(\d+ ...

Conquering the need for a 426 upgrade was a challenging task

For the past few months, I have been diligently working on a web application with Angular for the front end and Node/Express/Mongo for the backend. My setup involves running Angular on localhost:4200 and Node on localhost:3000. However, some members of ou ...

React Error: The module 'common' could not be located

I've been searching high and low on the web for a solution to this problem, but so far, nothing I've found has done the trick. I'm fairly new to React, but a friend of mine requested my assistance with some CSS work on his React project, so ...

Would it be unwise to create a link to a database directly from the client?

If I want to connect my React app to Snowflake all client-side, are there any potential issues? This web app is not public-facing and can only be accessed by being part of our VPN network. I came across this Stack Overflow discussion about making API cal ...

Material UI Grid's layout does not support placing a select element within a row

As a newcomer in the world of full stack development, I am delving into coding projects to enhance my understanding of frontend technologies like React JS and Material UI. My latest endeavor involves creating a page that displays posts from the backend in ...

Simulating Knex interactions using Sinon

I've been struggling to create unit tests for my NodeJs app using chai and sinon due to difficulties in mocking the knex query builder. In my app.js file, I initialize Knex as database and then incorporate it into my app's context. The specific ...

Utilizing directives while initiating dynamic components

I've been exploring the capabilities of dynamically creating components using the ComponentFactoryResolver. const factory = this.componentFactoryResolver.resolveComponentFactory(FooComponent); const component = this.templateRoot. ...

Adding a character to an AngularJS textbox

I am attempting to add the "|" Pipe symbol to a textbox when a button is clicked, using this function. $scope.appendPipe = function(){ var $textBox = $( '#synonyms' ); $textBox.val($textBox.val()+'|'); //textBox ...

Having trouble with syntax highlighting on Node.js Vash view files in Visual Studio 2015 Update 3?

While working on a Node.js application using Vash as the view engine in Visual Studio 2015 Update 3, I encountered an issue with syntax highlighting. When writing HTML in the vash files, the code appears as plain text without any syntax highlighting. For e ...

Error Message: Undefined Constructor for Firebase Google Authentication

Hey there! I've been working on integrating Firebase google authentication into my project. Unfortunately, I encountered an error while testing it out. Here's the error message that appeared in the console: Uncaught (in promise) TypeError: Cannot ...