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

Enhance your spreadsheet by incorporating dynamic columns utilizing xlsx and sheetjs libraries

I have an array consisting of multiple tags with unique ids and corresponding data: [ { "id": "tagID1", "error": { "code": 0, "success": true }, "data": [ [1604395417575, 108 ...

The Challenge of Referencing Javascript Files (including jQuery)

Previously, I had the following code snippet: <head> <script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script> <script type="text/javascript"> var optPrompt = "- Select One -"; var subCats ...

As I iterate through a MySQL array, JavaScript is able to manipulate the initial displayed data

I'm struggling to achieve the desired outcome with my code. It seems that when I iterate through an array of data, JavaScript only works on the first echoed data. Here is a snippet of the code: <?php $ids = array(); ...

JavaScript basic calculator app failed to generate an error as anticipated

For my homework assignment, I am developing a basic calculator application using JavaScript. My main task is to ensure that the input numbers are limited to only two and that they are valid numbers; otherwise, an error should be thrown. Initially, concern ...

transform nested object into a flat object using JavaScript

here is the given JSON format: - { "_id": "5c1c4b2defb4ab11f801f30d", "name": "Ray15", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afddced69e9aefc8c2cec6c381ccc0c2">[email protected]</a>" ...

Does an invisible property value exist?

Instead of: if ( ! $('#XX').is(':visible) ) Is there a property named invisible? I tested that one out, but it seems to not work. Appreciate the help! ...

The process of creating a React build varies greatly from the initial development phase

Thank you for offering to help me! After building my React web app, it looks very different from development mode. I use serve -s build to monitor the app build. However, even on my online DigitalOcean server, it doesn't appear the same as in develop ...

Guide on retrieving the innerHTML of all <a> tags within a specific span class

<span class="mgen"> <a rel="tag">Action</a> <a rel="tag">Adventure</a> <a rel="tag">Apocalypse</a> <a rel="tag">Fantasy</a> <a rel="tag" ...

Guide on showcasing an alert notification when the data is already existing within an array through javascript

Need help with displaying an alert message in JavaScript for duplicate values in an array? var names = []; var nameInput = document.getElementById("txt1"); var messageBox = document.getElementById("display"); function insert() { names. ...

Is it recommended to use Promise.await over async/await?

After starting some new operations in my project, I discovered that db.aggregate needed to be executed asynchronously: db.aggregate( [ { $match: { "records": { $e ...

Unable to retrieve cookie using getServerSideProps in Next JS

My goal is to retrieve and return two cookies, but I am running into an issue where only the token cookie is returned successfully, while the key cookie remains inaccessible. export async function getServerSideProps(ctx) { const cookies = ctx.req.header ...

Using AngularJS to Send Elements to Scripts and Selectors

When I use the following template: <div id="container"> <textarea name="message"></textarea> <button value="send" ng-click="testMethod($parent)"> </div> In the JavaScript code: $scope.testMethod = function(element) ...

Verify the presence of the promotion code and redirect accordingly

I have created a special promotion page that I want to restrict access to only users who have received a unique code from me via email. To achieve this, I have designed the following form: <form accept-charset="UTF-8" action="promotion.php" method="po ...

What is the process of converting a value from an HTML form into a PHP variable?

I am looking to update the order preparation time. I have created an HTML form, but I am facing issues passing it into a PHP variable after this code block. I have tried using Cookies and POST method, but neither has helped me so far. <form> ...

How many addresses are stored in the JSON file?

After verifying the JSON data and trying to determine the number of addresses, I encountered the following result when accessing the information: var location = req.body; The output obtained was: { AddressValidateRequest: { '-USERID': &ap ...

NodeJS npm module installed globally is unable to run the main/bin JavaScript file using node command

Here is an example of my package.json: { "name": "example-module", "version": "1.0.0", "bin": "./bin/example-module.js", "main": "./bin/example-module.js", "description": "Example module description", "homepage": "http://my.home.page.com", " ...

Why isn't URL Data displaying for the GET method in AJAX requests?

One interesting aspect of the GET method in AJAX is that it sends data through the URL. Despite this, when using AJAX with a GET request, why isn't the data visible in the URL? ...

Discover the capability to choose dates from different months using the DatePicker component from @material-ui/pickers

I am currently in the midst of a React project that requires the use of the DatePicker component from @material-ui/pickers. The specific mandate is to show dates outside of the current month and allow users to select those days without needing to switch m ...

Is it possible to utilize WebAssembly in JavaScript to access the memory of a C struct directly?

Looking at the C code snippet below, there is a struct defined as follows typedef struct { ValueType type; union { bool boolean; double number; Obj* obj; } as; } Value; The ValueType enum used in the struct is defined a ...

Issue with Angular 7: In a ReactiveForm, mat-select does not allow setting a default option without using ngModel

I have a Angular 7 app where I am implementing some reactive forms. The initialization of my reactive form looks like this: private initFormConfig() { return this.formBuilder.group({ modeTransfert: [''], modeChiffrement: [' ...