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

Guide to finding and saving email addresses from a string output: extracting and storing each one individually in a text file

After collecting data from multiple sources, the output I obtained is as follows: "addressId":"132234","businessEntryCount":2026},{"district":"Nordend-West","districtSlug":"frankfurt-am-main- ...

What steps should I take to modify my database while utilizing radio buttons in the edit mode?

I am experiencing an issue with the radio button functionality. When creating a new user.jsp, I am able to successfully add the value from the radio button to the database. However, when I attempt to edit the values in the jsp, the changes do not reflect i ...

Playing with Data in AG-Grid using Javascript

I am working on implementing data display using AG Grid with an AJAX call, but I am facing an issue where no data is being shown in the grid. Even though my AJAX call seems to be functioning correctly and returning the desired object List, the grid itsel ...

Switch navigation - always display the menu on the existing page

I have a toggle menu implemented. Please check out the code and functionality on JsFiddle When clicking on a h3 tag like Category 1 (which is an a tag), the menu opens and remains open on the current page. However, if you click on the h3 tag (Category1) ...

Prevent Purchase Button & Implement Modal on Store Page if Minimum Requirement is not Achieved

On my woocommerce shop page, I am facing an issue where all items are added to the mini-cart without meeting the minimum order requirement. This results in users being able to proceed to checkout without adding enough items to meet the minimum order amount ...

What is the reason behind JavaScript's `fn.length` returning the count of named parameters that `fn` function has?

Why does calling fn.length in JavaScript return the number of named arguments fn has? > function fn () { } > x.length 0 > function fn (a) { } > x.length 1 > function fn (a,b,c) { } > x.length 3 This behavior is quite peculiar. I wonde ...

Issue with removing npm and node from Mac OS 10.13.5 is causing uninstallation to fail

After following the instructions from this link on Stack Overflow to completely uninstall Node.js and reinstall it on my Mac OS X system, I have attempted all the suggested solutions. Despite this, when I open the command prompt and run commands node -v a ...

Using *ngIf to construct SVG icons in Angular 2 doesn't contribute to the DOM in any way

I am currently utilizing icoMoon to import a series of SVG icons. The structure of the html I'm trying to create using ngIf is as follows: <div class="contactIcon"> <svg class="icon icon-envelop"> <use xlink:href="symbol-d ...

Finding and removing the last portion of the innerHTML can be achieved by employing specific techniques

Looking to manipulate a <div> element that includes both HTML elements and text? You're in luck. I need to locate and remove either the last, nth-from-last, or nth plain text section within it. For example: <div id="foo"> < ...

I am using node.js with an express server, and I want to display any errors that I see in the console on my webpage as well

I have set up a Node.js Express server on Glitch website like this: const express = require("express"); const app = express(); const port = 3000; const server = app.listen(port, () => console.log(`App listening on port ${port}!`) ); Additionally, ...

When invoking a native prototype method, consider extending or inheriting object prototypes for added functionality

Recently, I came across a discussion on Inheritance and the prototype chain where it mentioned: Avoiding bad practice: Extension of native prototypes One common mis-feature is extending Object.prototype or other built-in prototypes. This practice, known ...

I'm sorry, but the command "node-inspector" cannot be

After attempting to run both node-inspector and node-debug app.js, I encountered the following error messages: zsh: command not found: node-inspector zsh: command not found: node-debug Interestingly, when running node --debug, I received: Debugger liste ...

Communication failure between React and Node containers when attempting to dockerize app

I am currently in the process of dockerizing a react-node application. I have successfully created a docker compose file for this purpose. However, I am facing an issue where the react container fails to resolve the IP address of the node container when tr ...

Forcing the Empty Table message in jQuery DataTables post an AJAX request

My configuration for jquery-datatables includes a custom search filter that acts as both the standard keyword filter and a specific Item ID search using an ajax call to retrieve a value from the back end, which is then used to search a particular column in ...

Issue encountered while retrieving data in React Native app from an express server

I am currently in the process of building an android application that fetches data from a local server. I have encountered no errors thus far, but unfortunately, I am not receiving the requested data. To provide some context, my frontend is built using Rea ...

Display information in a detailed table row using JSON formatting

I have set up a table where clicking on a button toggles the details of the corresponding row. However, I am having trouble formatting and sizing the JSON data within the table. Is there a way to achieve this? This is how I implemented it: HTML < ...

Node.js: step-by-step guide for sending secure HTTPS requests to an application with a self-signed certificate

I currently have two Node.js applications accessible through HTTPS. Both services are using self-signed certificates, and manual access to them works with the usual security warnings. However, I am facing an issue where one application cannot communicate w ...

Tips for linking a Google Meet invitation to a Calendar Event (generated using a Service Account)

Having trouble creating a basic API call to set up a Google Calendar event with a Google Meet link embedded in it. Despite consulting the Calendar API Documentation and trying different examples, I am still facing difficulties. My setup involves a Servic ...

I'm facing a challenge in transmitting data to my database

This is the function I am using to handle post requests in my application: app.post("/productos", async (req, res) => { try { const { nombre, precio, urlImagen, categoria } = req.body; console.log("Form data:", re ...

Determine whether there is only one array in the object that contains values

At the moment, I am attempting to examine an array in order to determine if only one of its elements contains data. Consider this sample array: playersByGender = { mens: [], womens: [], other: [] }; Any combination of these elements may contain dat ...