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 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.
As Kevin B stated, you have to install body-parser
locally and save it to the manifest:
npm install --save body-parser
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With