Error: Most middleware (like bodyParser) is no longer bundled with Express

61,409

Solution 1

You need to replace your old bundled middleware usage (express.bodyParser, express.methodOverride, express.errorHandler) with external/separate middleware. The link in the error gives you the names of these new middleware. You may want to check the documentation for these middleware to check for any API changes since Express 3.

Solution 2

EDIT: I have posted a fork of Brian's seed with all the changes given below: https://github.com/LossyHorizon/angular-socket-io-seed

I found this discussion while fighting this my self. I am updating my copy of
https://github.com/btford/angular-socket-io-seed before I begin a new project. I plan to submit my changes back to Brian Ford when I figure out how.

OLD package.json

    "socket.io": "~0.9.16",
    "jade": "~0.31.2",
    "express": "~3.2.6"

NEW package.json

    "socket.io": "1.1.*",
    "jade": "1.6.*",
    "express": "4.8.*",
    "serve-favicon": "2",
    "morgan": "1.3.*",
    "method-override":"*", //added missing ,
    "body-parser": "1.8",
    "errorhandler": "*",
    "express-session": "*",
    "multer": "0.1.*"

You will need to explicitly add the middle ware that used to be just present, one line:

    var express = require('express');

Becomes a bunch of lines:

    var express = require('express');
    var favicon = require('serve-favicon');
    var logger = require('morgan');
    var methodOverride = require('method-override');
    var session = require('express-session');
    var bodyParser = require('body-parser');
    var multer = require('multer');
    var errorHandler = require('errorhandler');

OLD setup code:

    app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.static(path.join(__dirname, 'public')));
    app.use(app.router);

NEW setup code:

    app.set('port', process.env.PORT || 3000);
    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')));

This is the part that took me forever. Sadly once I worked this out I looked in express/lib/application.js, searched for app.listen and there is a wonderful comment that explains things quite nicely. Not sure why I was so slow to look up the source, though it looks like I am not alone in that.

Demos, docs, most blog posts, say you start your app with this, and it works, but locks us out from using socket.io (http & https at the same time also).

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

This is functionally the same, but makes socket.io usage easy. Look up the source for app.listen() and you will see that this is what it is doing anyway.

    // could be/remain at top of file
    var http = require('http');    

    var server = http.createServer (app);
    // delete this line if NOT using socket.io
    var io = require('socket.io').listen(server);   

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

I does not matter if you use the new express 'standard' syntax, or this syntax, the same http object is used either way, and as I recall http is a built in component to node.js anyway.

I hope this helps someone else.

Solution 3

  • First you install bodyParser :

    npm install body-parser

  • And use it:

    var bodyParser = require('body-parser'); 
    app.use(bodyParser.urlencoded({
        extended: true
    }));
    app.use(bodyParser.json());
    

Solution 4

I am having a similar problem, and havent been able to resolve it yet.

But as per my reading, from various sources you need to:

  1. Either update your package.json to include the dependencies for all the middleware like:

     "dependencies": {
                       "express": "*",
                       "body-parser": "*",
                       "method-override": "*",
                      .
                      .
                      .  
                    }  

    or you can just run each one separately on the command prompt as

    npm install body-parser --save-dev

    You will have to do this for the middleware that you use out of the short list shown here or the complete list here.

    As far as I can make out, in your code, you are using: body-parser, method-override, static and errorhandler.

  2. You will have to remove the line:

     app.use(app.router); 
    as described here

As I said, I am also, working on it. I suggest you make the changes, and tell me if the error on the console changes.

Share:
61,409
Admin
Author by

Admin

Updated on July 18, 2020

Comments

  • Admin
    Admin almost 4 years

    I need to create a web service and I am using Node.js in server. But when I am running in localhost I am getting an error:

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

    neo4jtest.js

    var config = require('./config');   
    var bodyParser = require('body-parser'); 
    
    var app = express();
    
    var neo4jurl = process.env.NEO4J_URL ;
    neo4jurl = neo4jurl +'/db/data/';
    
    var query = [ 'START me=node:node_auto_index(name={inputusername}) MATCH me<--friend<--friend_of_friend where (friend_of_friend.entitytype={inputentitytype}) RETURN friend_of_friend;' ];
    var insertquery = [ 'CREATE (user {entitytype:{inputentitytype}, name : {inputname}}) return user;' ];
    var queryforallrelation = [ 'start n = node:node_auto_index(name={inputusername}) match(n)--(x)  return x;'];
    
    // Config
    
    
        var env = process.env.NODE_ENV || 'development';
        if ('development' == env) {
        // configure stuff here
        app.use(express.bodyParser());
        app.use(express.methodOverride());
        app.use(app.router);
        app.use(express.static(path.join(application_root, "public")));
        app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
        }
    
    app.get('/api', function (req, res) {
      res.send('REST API is running');
    });
    
    app.get('/friendoffriend/:username', function (req, res){
        res.set({'Content-Type': 'text/json'});
        username = req.params.username;
        type = 'user';
        neo4j.connect(neo4jurl, function (err, graph) {
    
                graph.query(query.join('\n'), {inputusername : username, inputentitytype :type} ,function (err, results) {  
                    if (err) {
                        res.send(HTTPStatus.INTERNAL_SERVER_ERROR,'Internal Server Error');
                    }
                    else {
                        res.send(HTTPStatus.OK,JSON.stringify(results));
                    }
                }); 
        });
    });
    
    app.get('/insertuser/:username', function (req, res){
        res.set({'Content-Type': 'text/json'});
        username = req.params.username;
        type = 'user';
        neo4j.connect(neo4jurl, function (err, graph) {
                graph.query(insertquery.join('\n'), {inputname : username, inputentitytype :type} ,function (err, results) {    
                    if (err) {
                        res.send(HTTPStatus.INTERNAL_SERVER_ERROR,'Internal Server Error');
                    }
                    else {
                        res.send(HTTPStatus.OK,JSON.stringify(results));
                    }
                }); 
        });
    });
    
    //Cypher Query with Javascript Callback Example
    
    function neo4jQuery(neo4jurl, query, parameters, giveresults) {
        neo4j.connect(neo4jurl, function (err, graph) {
            graph.query(query.join('\n'), {inputusername : 'andrew'} ,function (err, results) { 
                if (err) {
                    giveresults(HTTPStatus.INTERNAL_SERVER_ERROR);
                }
                else {
                    giveresults(JSON.stringify(results));
                }
            }); 
        });
    }
    
    app.get('/allrelations/:username', function (req, res){
        res.set({'Content-Type': 'text/json'});
        username = req.params.username;
        parameters = {inputusername : username};
        neo4jQuery(neo4jurl, queryforallrelation, parameters, function(results){
            res.send(results);
        });
    });
    
    
    
    app.listen(1212);
    

    Following is the error that i got from the console:

    C:\node\NodejsNeo4j1-master>node neo4jtest.js
    
    Error: Most middleware (like bodyParser) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
        at Function.Object.defineProperty.get (C:\node\NodejsNeo4j1-master\node_modules\express\lib\express.js:89:13)
        at Object.<anonymous> (C:\node\NodejsNeo4j1-master\neo4jtest.js:26:18)
        at Module._compile (module.js:456:26)
        at Object.Module._extensions..js (module.js:474:10)
        at Module.load (module.js:356:32)
        at Function.Module._load (module.js:312:12)
        at Function.Module.runMain (module.js:497:10)
        at startup (node.js:119:16)
        at node.js:906:3
    
  • Admin
    Admin over 9 years
    Thanks!!! Sir, How to replace the old bundled middleware?? Can you please tell me the steps.
  • JRichardsz
    JRichardsz about 6 years
    if you want update your package.json : npm install body-parser --save