20

I'm beginning to learn node.js and trying to work out how to get the contents of a POST request. I am trying to follow the instructions in this post. So far I have successfully installed node.js (on Windows 7) and express, and been able to get my very first script to work. However my problem comes when I try to use body-parser. I have installed it and it appears to be there (here is a screenshot)

Here is the code of the node.js script

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(express.json());       // to support JSON-encoded bodies

app.get('/', function(req, res) {
    res.setHeader('Content-Type', 'text/plain');
    res.end('Vous êtes à l\'accueil');
});

app.get('/user/:usernum', function(req, res) {
    res.setHeader('Content-Type', 'text/plain');
    res.end('You are on page USER with n° : ' + req.params.usernum);
});

// https://stackoverflow.com/questions/5710358/how-to-get-post-a-query-in-express-js-node-js
app.post('/adonis', function(req, res) {
    res.setHeader('Content-Type', 'text/plain');
    console.log(req.body.title);
//    res.write(JSON.stringify(req));
    res.end('Hopefully I stringified a POST');
});

// ... Tout le code de gestion des routes (app.get) se trouve au-dessus

app.use(function(req, res, next){
    res.setHeader('Content-Type', 'text/plain');
    res.status(404).send('Page introuvable !');
});

app.listen(8091);

Yet when I run it, node.js throws an error saying "cannot find module body-parser". What have I done wrong?

As per @Kale's and others' suggestions I tried installing body-parser locally, but this does not seem to help since now my script gives the following message:

Error: Most middleware (like json) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
at Function.Object.defineProperty.get (d:\smartguide\nodejs\node_modules\express\lib\express.js:99:13)
at Object.<anonymous> (d:\smartguide\nodejs\oc1.js:5:16)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3`

I tried installing "json" locally and globally - the install seems to work but it makes no difference to the file error.

Community
  • 1
  • 1
Martin K
  • 439
  • 1
  • 6
  • 17

4 Answers4

37

As Kevin B stated, you have to install body-parser locally and save it to the manifest:

npm install --save body-parser
Taylor Swanson
  • 613
  • 7
  • 11
  • Having installed body-parser locally (as per @Kale), I now get the following error: – Martin K Aug 24 '15 at 12:25
  • This is a common error when deploying node with heroku, and it happens when you do not add body-parser within `package.json` dependencies at your app root folder `"dependencies": { "body-parser": "^1.17.2", ...` – Junior Mayhé Aug 07 '17 at 15:51
8

This answer is much simpler. Go to the base directory and link to the required global modules.

npm link body-parser

There's no need to install modules all over the place. If the module is not installed globally, the above command will install the module globally then link to it locally.

Shea Hunter Belsky
  • 2,815
  • 3
  • 22
  • 31
  • In case this helps anyone, I dont have ```body-parser``` anywhere in my ```package.json``` so I was confused when the error reported ```cannot find module body-parser```. I solved the issue by essentially reinstalling - deleting the ```node_modules``` folder and running the ```npm install```command. – Joel Balmer Jun 27 '18 at 18:45
3

I think I was doing something fundamentally wrong - I went back to basics and started all over again, this time making sure I had a package.json file. Now it works.

Here is the code:

var express = require('express');
var session = require('cookie-session');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var jsonParser = bodyParser.json();

var app = express();


// JSON testing
app.post('/json-test', jsonParser, function(req, res) {
    if (!req.body) return res.sendStatus(400);
    console.log(JSON.stringify(req.body));
    console.log(req.body.title);
    res.status(200).send(req.body.title);
    })

// Can't get anything else
.use(function(req, res, next){
    res.setHeader('Content-Type', 'text/plain');
    res.status(404).send('Page introuvable !');
    })


.listen(8090);

And here is the package.json

{
"name": "todo1",
"version": "0.1.0",
"dependencies": {
    "express": "~4.11.0",
    "ejs": "~2.1.4",
    "cookie-session": "~1.1.0",
    "body-parser": "~1.10.1"
},
"author": "Martin",
"description": "Un gestionnaire de todolist ultra basique"
}
Martin K
  • 439
  • 1
  • 6
  • 17
0

I was getting the same error where after installing express I am getting errors like

Cannot find module 'body-parser' after installing this the error is

Cannot find module 'merge-descriptors' and so on for

Cannot find module 'finalhandler'

Cannot find module 'array-flatten'

These all module are dependencies for express. If you execute "npm install" or "npm install -g" without any module it will install all the missing dependencies.

To fix this I first uninstall the express and then install the same and immediately after that executed "npm install". This fixed all the errors.

Rahul Sonone
  • 2,685
  • 1
  • 27
  • 38