azat-co / expressworks

Learn Express.js from the author of one of the best books on Express.js—Pro Express.js— with this workshop that will teach you basics of Express.js.
MIT License
709 stars 220 forks source link

"Good Old Form: Official solution gives: Error: Cannot find module 'body-parser' #94

Closed mhurwicz closed 8 years ago

mhurwicz commented 8 years ago

The official solution:

    var express = require('express')
    var bodyParser = require('body-parser')
    var app = express()    
    app.use(bodyParser.urlencoded({extended: false}))
    app.post('/form', function(req, res) {
      res.send(req.body.str.split('').reverse().join(''))
    })   
    app.listen(process.argv[2])

gives: Error: Cannot find module 'body-parser'

But this works:

var express = require('express');
var app = express();
app.use(express.urlencoded({extended: false}));
app.post('/form', function(req, res) {
    res.end(req.body.str.split('').reverse().join(''));
});
app.listen(process.argv[2]);
TylerMoeller commented 8 years ago

I'm not able to reproduce this with Node 5.0 on Windows 7, Windows 10, or Mac OS. What OS and Node version are you running?

I only see the error Cannot find module 'body-parser' when I do not have the body-parser module installed. Run npm install body-parser to fix it.

If I run your code that uses express as middleware, I get an error:

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

azat-co commented 8 years ago

@mhurwicz you must be running express v3.x. they used to have body parser in the framework itself, not the case with 4.x anymore so you're getting cannot find with the official solution (which is for v4.11.2)

I think you might have two conflictiong versions... try

$ npm uninstall -g express

then in your project folder execute what @TylerMoeller suggested

$ npm init
$ npm body-parser@1.12.0

You have to use npm init or have package.json or node_modules. Otherwise your local install might end up being God know where.

Starting at the $PWD, npm will walk up the folder tree checking for a folder that contains either a package.json file, or a node_modules folder. If such a thing is found, then that is treated as the effective "current directory" for the purpose of running npm commands. (This behavior is inspired by and similar to git's .git-folder seeking logic when running git commands in a working dir.)

From https://docs.npmjs.com/files/folders#more-information