0

I am trying to get parameters from a POST in the variable postData by using the request by - ( i used this because it was suggested here - How do I get the post request with express js? )

and here - How to retrieve POST query parameters?

var express = require('express');
var app = express();
var fs = require('fs');
var json = require('json');
app.use(express.json());       // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodies

app.post('/shrib/:file/:data',function(req,res){
    var fileName = req.params.file;
    var data = req.params.data;
    req.on('data',function(data){ body+=data; } );
    req.on('end' ,function(){
        var postData = qs.parse(body);
        var writeStream = fs.createWriteStream(fileName);
        var postData = req.body.text;
        if(postData)
            console.log(postData);
        else    
            console.log("failed miserably");
        res.write(200);
        res.end();
    });
});
app.get('/shrib/:file',function(req,res){   
    var fileName = req.params.file;
    if(fileName != ''){
        var readStream = fs.createReadStream(fileName);
        var content;
        readStream.on('data',function(chunk){
            content+=chunk.toString();
            console.log(content);
        });
        readStream.on('end',function(){
            res.writeHead(200,{"Content-Type":"text/html"});
            res.write("<form id=\"submitForm\" method=\"POST\">");
            res.write("<textarea id=\"text\"rows=50 cols=50 >");
            console.log(content);
            if(content)
                res.write(content.toString());
            res.write("</textarea>");
            res.write("<input type=\"submit\" value=\"submit\" />");
            res.write("</form>");
            res.write("<script>");
            res.write("var windowLocation = location.href;");
            res.write("document.getElementById(\"submitForm\").action=windowLocation + \'/data\';");
            res.write("</script>");
            res.end();
        });
    }else{
        res.writeHead(200);
        res.write("invalid/empty path name"); 
    }
});
app.listen(8080);

and got this error -

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 (/home/unknown/public_html/node/node_modules/express/lib/express.js:89:13)

I was using body parser before which i read in some solutions here and it gave me the same error middleware missing, i installed it globally then also got the same error and after that i read about json , so i installed it globally using

npm install -g json

did not work, then too. then i tried adding the dependancies -

{
  "name": "express_shrib.js",
  "version": "0.0.1",
  "description": "Creating Shrib Using Express",
  "main": "express_shrib.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/iamdeadman/nodejs.git"
  },
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/iamdeadman/nodejs/issues"
  },
  "homepage": "https://github.com/iamdeadman/nodejs",
  "dependencies": {
    "express": ">= 1.2.0",
    "json": ">= 9.0.0"
  }
}

and ran npm install still the same error -

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 (/home/unknown/public_html/node/node_modules/express/lib/express.js:89:13)

Edit** - Code with the new body-parser module

var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
app.use(bodyParser());
app.post('/shrib/:file/:data',function(req,res){
    var fileName = req.params.file;
    var data = req.params.data;
    req.on('data',function(data){ body+=data; } );
    req.on('end' ,function(){
        var postData = req.body;
        var writeStream = fs.createWriteStream(fileName);
        if(postData)
            console.log(postData);
        else{   
            console.log("failed miserably");
            console.log(postData);
        }
        res.writeHead(200);
        res.end();
    });
});
app.get('/shrib/:file',function(req,res){   
    var fileName = req.params.file;
    if(fileName != ''){
        var readStream = fs.createReadStream(fileName);
        var content;
        readStream.on('data',function(chunk){
            content+=chunk.toString();
            console.log(content);
        });
        readStream.on('end',function(){
            res.writeHead(200,{"Content-Type":"text/html"});
            res.write("<form id=\"submitForm\" method=\"POST\">");
            res.write("<textarea id=\"text\"rows=50 cols=50 >");
            console.log(content);
            if(content)
                res.write(content.toString());
            res.write("</textarea>");
            res.write("<input type=\"submit\" value=\"submit\" />");
            res.write("</form>");
            res.write("<script>");
            res.write("var windowLocation = location.href;");
            res.write("document.getElementById(\"submitForm\").action=windowLocation + \'/data\';");
            res.write("</script>");
            res.end();
        });
    }else{
        res.writeHead(200);
        res.write("invalid/empty path name"); 
    }
});
app.listen(8080);

and here i get

{}

in the console which means that the body object is empty for some reason.

Community
  • 1
  • 1
Harshit Laddha
  • 2,044
  • 8
  • 34
  • 64

2 Answers2

1

With Express 4, the body parsing middleware (like other previously built-in middleware) was extracted out into the 'body-parser' module. However, this new module only handles JSON and urlencoded form submissions, not multipart.

If you need multipart support, you'd need to use something like connect-busboy or multer or connect-multiparty (connect-multiparty is essentially the old Express bodyParser middleware).

EDIT: Also, the name attribute is missing for the textarea input field. This is required, otherwise the field will not be sent with the form.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • Okay so i added npm install body-parser -g and then app.use(bodyParser()); and then tried var postData = req.body.text; console.log(postData); – Harshit Laddha Jun 08 '14 at 15:42
  • But still it gave me undefined in the console.log() – Harshit Laddha Jun 08 '14 at 15:43
  • Okay, on printing req.body i got {} just this, can you suggest why the data from text id is not getting posted – Harshit Laddha Jun 08 '14 at 15:51
  • You should probably post the code you're using now with `body-parser` somewhere. – mscdex Jun 08 '14 at 16:00
  • I edited my post for the body-parser code, which i found from http://expressjs.com/guide.html#error-handling and https://github.com/expressjs/body-parser though i did not understand why to wrap the parsing code in the use function, is that necessary ? or the way i am doing is correct but the form i am posting in response is wrong – Harshit Laddha Jun 08 '14 at 16:23
  • @deadman Try [this code](https://gist.github.com/anonymous/686b860ebe245fd07422). – mscdex Jun 08 '14 at 17:26
  • Oh, yeah it worked. Thanks a lot, was it the quotes that i used in the form that messed the post data or anything else, i did not understand as the body-parser code usage was similar to mine i think – Harshit Laddha Jun 08 '14 at 17:33
  • @deadman It may have been the missing `name` attribute for your textarea field. – mscdex Jun 08 '14 at 17:36
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/55283/discussion-between-deadman-and-mscdex). – Harshit Laddha Jun 08 '14 at 17:43
0

When using express 4 use body-parser middleware to get parameters. Multipart has issue that it creates loads of temp files. So its better to avoid it whenever possible and use upload services directly.

app.use(function (req, res, next) {
        var urlParser = require('url');
        var url = urlParser.parse(req.url, true);
        if (url.pathname == "/rest/file/upload") {
            next();
        } else {
            var contentType = req.header("content-type");
            if (contentType && contentType.indexOf("application/json") != -1) {
                bodyParser.json({limit: 1024 * 1024 * 10})(req, res, next);
            } else {
                bodyParser.urlencoded({ extended: true, limit: 1024 * 1024 * 10})(req, res, next);
            }
        }
    });

then just get your request parameter as :

console.log(req.param("parameter-name"));
vashishatashu
  • 7,720
  • 7
  • 29
  • 34