In NodeJS, many middleware must be installed individually, such as bodyParser

While attempting to set up my application, which employs multiple middlewares including body-parser, I encountered the following error:

Error: Most middleware (like bodyParser) is no longer bundled with Express and must be installed separately. Please refer to https://github.com/senchalabs/connect#middleware.

I separately installed body-parser using:

npm i body-parser

The NodeJS code snippet in question is as follows:

// Server definitions

var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
const neo4j = require('neo4j-driver').v1;

var restify = require('restify');
var expressJwt = require('express-jwt');
var session = require('express-session');
var config = require('./config.json')
var app = express();

var router = express.Router();

var port = 3003;
app.use(restify.plugins.bodyParser());
app.use(express.bodyParser());
var bodyParser = require('body-parser'); 
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.set('port', process.env.PORT || 3003);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(methodOverride());
app.use(session({ resave: true, saveUninitialized: true, secret: 'uwotm8' }));

// parse application/json
app.use(bodyParser.json());                        

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// parse multipart/form-data
app.use(multer());

app.use(express.static(path.join(__dirname, 'public')));


app.use(bodyParser.json());

app.use(bodyParser.json({ type: 'application/vnd.api+json' })

app.use(cors());

app.use(session({ secret: config.secret, resave: false, saveUninitialized: true }));

var multer = require('multer');
var path = require('path');
var app = express();
var mkdirp = require('mkdirp')
var port = 3003;

var myModule = require('./api-mine-server/api-mine-controller.js');

app.use(express.static(path.join(__dirname, 'uploads')));

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

var storage = multer.diskStorage({

    destination: function (req, file, cb) {
       //code
        });
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    }

});
var upload = multer({ storage: storage });

app.post("/upload", upload.array("uploads[]", 12), function (req, res) {

    //code
});

// -----------------  File Uploader code  ends  -------------------------

app.listen(app.get('port'), function(){
    console.log('Express server on port ' + app.get('port'));
 });

var server = app.listen(port, function () {
    console.log("Listening on port %s...", port);
});

Answer №1

It is important to remove the line app.use(express.bodyParser()); because it relies on the body-parser from express, which can cause an error.

Many middleware packages, such as bodyParser, are no longer included with Express and must be installed independently

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

Employ ImageMagic in a synchronous manner

Consider utilizing imagemagick Required to use imagemagick in a synchronous manner. Meaning the following code should execute only after the image conversion is complete (regardless of any errors). The only solution I can see involves using deasync: co ...

Error: guild is not defined | discord.js

Having trouble with a ReferenceError that says guild is not defined? I recently encountered a similar issue with members but managed to fix it by adding a constant. As someone new to javascript and node.js, I could use some assistance. I've even tried ...

`The Art of Curved Arrows in sigjma.js, typescript, and npm`

I have encountered an issue while trying to draw curved arrows in sigma.js within my TypeScript npm project. The error occurs on the browser/client-side: Uncaught TypeError: Cannot read properties of undefined (reading 'process') at Sigma.pro ...

Eliminating the need for session and socket pooling in Sails.js

Hello, I am currently developing my rest api app using sails. I came across an interesting article on improving Node.js performance, which you can find here. One of the suggestions in point 2 was to eliminate socket pooling by setting options.agent to fal ...

Is there a way for me to determine the necessary URL for initiating my Get request?

I've been attempting a GET request to the endpoint /wp-json/wc/v3/products in order to test my WooCommerce API connection with POSTMAN. Unfortunately, I keep receiving a 404 error. I'm currently working on localhost, with WordPress running on por ...

Unable to transmit an object using ExpressJS

Greetings. I am currently trying to comprehend ExpressJS. My goal is to send a simple object from the express server, but it only displays "cannot get" on the screen. app.get("/", (req, res, next) => { console.log("middleware"); const error = true; ...

Encountering an error while attempting to generate a fresh Ionic 3 project. npm reports the following issue: "npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! [email protected] postinstall

Today has been a rough day as I attempt to start a new project in Ionic 3. The versions of software I am using are as follows: Ionic 3.9.2 npm 6.7.0 node v8.10.0 Operating on Ubuntu 18, each time I run the following command: sudo ionic start test blank ...

Avoid encountering a mandatory field error when utilizing the save() function

I am currently enrolled in a course that is outdated, and unfortunately, there is no one available to answer my questions. I'm hoping the information provided will suffice. I have a concern about not receiving a required field error when using the sa ...

The npm error code ENOTEMPTY arises due to a renaming operation that cannot be executed because the

Encountering an issue while trying to initialize a react-native project on my Mac. Can anyone provide guidance on how to resolve this error? I am using a Mac. Need to install the following packages: react-native Ok to proceed? (y) y npm ERR! code ENOTE ...

Guide to integrating Google APIs with SailsJS

Can someone help me calculate the distance between 2 coordinates using GMap API? I am trying to figure out how to retrieve data from a URL. https://maps.googleapis.com/maps/api/distancematrix/json?origins=Seattle&destinations=San+Francisco&key={{m ...

Running the `npm run coverage` command results in an error message stating: "Function 'require(...).internalModuleStat' is not

We're encountering a strange issue while running our tests. When we use the command npm run test, everything seems to be passing without any problems. However, when we switch to npm run coverage, some of the tests fail with the following error message ...

Error encountered with Node.js zlib not recognizing a certain method

After installing the ebay-api package via npm, I encountered an issue with one of its dependencies called restler. It seems to be throwing an error related to a method called 'gunzip' that I cannot resolve. TypeError: Object #<Object> has ...

Guide to Making a Cookie Using Node's cookie-session Package

I'm currently working on a small node application and my goal is to have it create a cookie for every visitor, named 'session', which will store the session ID. However, I've been facing some challenges in getting node to generate this ...

Exploring the depths of MongoDB Atlas using Express

Hello everyone, I am currently working with data stored in MongoDB Atlas using my Mongoose Schema. You can view my Mongoose Schema here. Also, here is the client side interface here. import React, { useState, useEffect } from 'react'; import { ...

Establishing parameters in a Socket.io chatroom

I am encountering an issue when attempting to store information in the socket room variables. The error message I receive is: UnhandledPromiseRejectionWarning: TypeError: Cannot set property 'host' of undefined This is the snippet of my code: io ...

Navigating through: How to access app.set() configurations within routes

When working with Express, I have been informed that global app settings can be created by implementing something similar to the following in my main app.js file: var express = require('express'), ... login = require('./routes/login ...

The process of running `npm install` within a Docker environment consistently results in data

I have been encountering a recurring issue with all the docker images I attempt to create, where they become corrupted during the npm install process. Specifically, two of the images displayed errors like: [stage-1 4/5] RUN npm install -g pm2 --loglevel w ...

Having trouble with yarn install? Keep receiving the error message "Other managers are not allowed"?

Recently, I began using the yarn package manager for one of my projects. To get started, I globally installed yarn using sudo npm install yarn -g. However, when attempting to install dependencies with yarn install, I encountered the following message on t ...

Create a Mongoose model that includes a field containing an array of ObjectID's

I am encountering an issue with my object named company, which contains keys for name(String) and locations(Array). Within the locations key, I want to include a user-generated key called name, as well as a second key generated using ObjectID. However, I a ...

Getting an error message stating "Cannot update headers after they have been sent" while working with Node.js/Express and Axios

I encountered the following error and need assistance in finding a workaround. My goal is to output the data as a JSON object. Is there a solution to navigate around this error? I am currently copying and pasting from a tutorial, but I can't pinpoint ...