Body Parser causing unexpected output

Currently encountering an issue when attempting to log the body of a POST request in my console. Despite seeing the payload in my Chrome console with the correct data, I am receiving the following error:

express_1  | TypeError: Cannot read property 'exampleval' of undefined

This logic has worked for me without any problems in the past.

services/router.js

const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
var app = express();
    // parse application/json
    app.use(bodyParser.json());                        

    // parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: true }));
const router = new express.Router();
const employees = require('../controllers/employees.js');


//router.route('/employees').post(employees.post);

router.post('/employees', function (req, res) {
    var exampleval = req.body.exampleval;
    console.log(exampleval);
})

module.exports = router;

services/web-server.js

const http = require('http');
const express = require('express');
const webServerConfig = require('../config/web-server.js');
const bodyParser = require('body-parser');
const router = require('./router.js');
const morgan = require('morgan');
const cors = require('cors');


let httpServer;

function initialize() {
  return new Promise((resolve, reject) => {
    const app = express();
    httpServer = http.createServer(app);
    // Combines logging info from request and response
    app.use(morgan('combined'));
    // enable cors on all routes
    app.use(cors())
    // Mount the router at /api so all its routes start with /api
    app.use('/api', router);
    // Body Parser
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: false}));

    httpServer.listen(webServerConfig.port)
      .on('listening', () => {
        console.log(`Web server listening on localhost:${webServerConfig.port}`);

        resolve();
      })
      .on('error', err => {
        reject(err);
      });
  });
}

module.exports.initialize = initialize;

function close() {
    return new Promise((resolve, reject) => {
      httpServer.close((err) => {
        if (err) {
          reject(err);
          return;
        }

        resolve();
      });
    });
  }

module.exports.close = close;

I believe these are the only essential sections of code. Any guidance on how to resolve this issue would be highly appreciated as my goal is to eventually utilize these values in an SQL query.

Answer №1

Sequence of middleware is crucial.

// Set up the router to start all routes with /api
app.use('/api', router);
// Include Body Parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

This arrangement ensures that

// Include Body Parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
// Set up the router to start all routes with /api
app.use('/api', router);

so that the router only handles requests after the body parser has added req.body.

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

Bar graph constructed using a pair of div elements

I extracted two values from an array: $target = $data->data[2][32][3]; For this particular example, $target = 9.83%. $clicks = $data->data[1][32][3]; And in this case, $clicks = 7.15%. I have created a bar-like chart using three main div elements ...

Guide to implementing optional localization strings in React-Router paths

Incorporating react-router, I aim to implement internationalization for links following this format: domain.com/langISO/countryISO2/page Here are some examples of valid routes: domain.com/ -> Home Page domain.com/en/us -> Home Page domain.com/fr/f ...

Data sent as FormData will be received as arrays separated by commas

When constructing form data, I compile arrays and use POST to send it. Here's the code snippet: let fd = new FormData(); for (section in this.data.choices) { let key = section+(this.data.choices[section] instanceof Array ? '[]' : '& ...

Resolving the bothersome complications of self-looping steps in jQuery animate delay

My timeline definition includes selectors and a sequence of delays and animations to apply to an object. I have also provided the option to loop through the steps for a specific object. Here is the function that I use to queue the animations: function an ...

Images showing Strava heat maps retrieved through API

Check out this amazing heatmap created by Strava! I'm curious about how they were able to achieve this - it seems like they are using the API to request overlay images based on the network tab. I have my own geo data, but I'm wondering how I can ...

How come React-Native isn't displaying successfully retrieved data using Axios?

I recently installed axios using the command below: npm i axios After writing the code below, I encountered an issue where React-Native doesn't display any data or throw any errors: import React, {useState, useEffect} from 'react'; import a ...

ui-jq flot graph with lazy loading

I am working with this HTML code: <div id="test" ui-jq="plot" ui-options=" [ { data: {{line}}, points: { show: true, radius: 6}, splines: { show: true, tension: 0.45, lineWidth: 5, fill: 0 }, label: 'Akademi' }, ], { ...

npm: Generating debug and production builds while ensuring accurate dependency management

I am in the process of developing a single page application using TypeScript along with various other dependencies such as jQuery, immutable, lodash, and React. Each resulting module is integrated into the project using requirejs. My goal is to generate t ...

Combining Arrays in AngularJS with an owl-carousel Setting

My goal is to implement an endless scrolling carousel in AngularJS using owl-carousel. The idea is to load new items every time the carousel is fully scrolled and seamlessly merge queried elements with the existing list. However, I've encountered a pr ...

Incorporate a pseudo class to a unique custom template or directive within an Angular project

I have been developing a custom dropdown menu directive in AngularJS. The issue I'm facing is that the buttons in my template become inactive when interacting with the dropdown menu, unlike a regular HTML select which remains active while the dropdown ...

Increase the quantity with animation

I am attempting to increment a number within an element on the page. However, I require the number to have a comma included while the increment should only increase by 1 digit every second. The code is currently functional, but I am facing a dilemma regar ...

Tips for sending the ampersand character (&) as a parameter in an AngularJS resource

I have an angular resource declared in the following manner: angular.module('xpto', ['ngResource']) .factory('XPTO', function ($resource, $location) { var XPTO = $resource($location.protocol() + '://' + $locatio ...

Enhancing HTML "range" element with mouse scroll functionality for incrementing values in step increments

I'm working on developing a scroll feature that operates independently from the main window's scrolling function. I aim to trigger specific events in the primary window based on interactions with this separate scrollbar. The only solution I coul ...

Bug Alert: Incompatibility between Angular $resource and PHP causing issues with Update and Delete functionalities

As a newcomer to both AngularJS and PHP, I have been struggling to find comprehensive documentation on using $resource to update records in a database. While I did come across a helpful tutorial here that covers most aspects of $resource usage, I am having ...

How can I dynamically update a div without refreshing the page by using an onclick event on a

When working on my project, I found helpful insights from this Stack Overflow thread. The structure of template-comparison.php involves fetching code from header.php to ensure the page displays properly. However, the actual "fetch code" process remains un ...

Sending information to a Flask application using AJAX

Currently, I am working on transferring URLs from an extension to a Flask app. The extension is able to access the current URL of the website. I have set up an AJAX request to connect to Flask, and the connection is successful. However, when trying to send ...

Using the spread operator in ES6 allows for arguments to be placed in a non-con

When working in nodeJS, my code looks like this: path = 'public/MIN-1234'; path = path.split('/'); return path.join( process.cwd(), ...path); I was expecting to get: c:\CODE\public/MIN-1234 but instead, I got: `‌publ ...

Is it possible to enable sorting for every column in the b-table component?

After reviewing the information on sorting per column in the bootstrap-vue documentation, I am curious if it is possible to enable sorting for the entire table. ...

ng-repeat not displaying any content

I am trying to create a form where users can input extra information by adding new rows, but I am struggling with generating the first row <div ng-repeat="row in rows"> <input type="text" placeholder="name"><input type="tel" placeholder="te ...

Difficulty executing for loop due to multiple buttons, resulting in malfunctioning buttons in JavaScript code

Currently encountering an issue while trying to implement modal windows on my first website. Everything works fine without the for loop, but I wanted to have multiple buttons and windows, so I decided to use a for loop to handle each button. Strangely, the ...