EzDevInfo.com

body-parser

Node.js body parsing middleware

How can I use body-parser with LoopBack?

I see that LoopBack has the Express 3.x middleware built-in. Indeed, body-parser is in loopback/node_modules. But I cannot figure out how to use it as middleware. I have never worked with Express 3.x, so maybe it's just that. require does not work, obviously, unless I install body-parser as a dependency in my project.

What should I do in server.js to use body-parser so that web forms are parsed into req.params? That's what it does, right?


Source: (StackOverflow)

Can I use multiparty for a single route in my express app?

I have an Express 3 app that uses bodyParser for most routes. (Most routes only accept multipart.) I have a single route that is going to be parsing files up to 1GB in size which bodyParser can't seem to handle. I would like to use multiparty for only this route so I don't have to rewrite the whole API. Is this possible?


Source: (StackOverflow)

Advertisements

Node.js (with express & bodyParser): unable to obtain form-data from post request

I can't seem to recover the form-data of a post request sent to my Node.js server. I've put below the server code and the post request (sent using postman in chrome):

Post request

POST /api/login HTTP/1.1
Host: localhost:8080
Cache-Control: no-cache

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="userName"

jem
----WebKitFormBoundaryE19zNvXGzXaLvS5C

NodeJS server code

var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(bodyParser());

app.all('/*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type,accept,access_token,X-Requested-With');
    next();
});

var port = process.env.PORT || 8080;        // set our port

var router = express.Router();              // get an instance of the express Router

router.get('/', function(req, res) {

    res.json({ message: 'I am groot!' });   
});

// Login
router.route('/login')

    .post(function(req, res){

        console.log('Auth request recieved');

        // Get the user name
        var user = req.body.userName;

        var aToken = getToken(user);

        res.json({

            'token':'a_token'
        });
    });

app.use('/api', router);

app.listen(port);

The login method tries to obtain the req.body.userName - however, req.body is always empty. I've seen other cases on SO describing such behavior but none of the related answers did apply here.

Thanks for helping out.


Source: (StackOverflow)

Node post message with large body (1.3 mb) error : 413 Request Entity Too Large

with fiddler Im creating post message with header

content-Type application/text-enriched

app.post('/books',function(req,res){
        var writeStream  = fs.createWriteStream('C://Books.txt' ,{ flags : 'w' });
        writeStream.write(req.body)

I was able to stops in debug in var writestream but when i excute this line I got error Entity is too large

there is some technique to overcome this problem? I wanted just to send large text file...

after reading some posts I've added the following which doesnt help...

var bodyParser = require('body-parser');

    app.use( bodyParser.json({limit: '2mb'}) );       
    app.use(bodyParser.urlencoded({     
        extended: true,
        keepExtensions: true,
        limit: '2mb', 
        defer: true 
    }));

UPDATE

I've also tried with the following

  app.use(bodyParser.raw({ type: 'application/text-enriched' }));
    app.use( bodyParser.raw({limit: '10mb'}) );
    app.use(bodyParser.urlencoded({     
        extended: true,
        keepExtensions: true,
        limit: '10mb', 
        defer: true
    }));

also got the same error...413 Request Entity Too Large


Source: (StackOverflow)

Parsing nested JSON using body-parser and express

I have an iOS app which is sending a JSON packet to a webserver. The webserver code looks like this:

var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
mongoose.connect('mongodb://localhost/test');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
  console.log("MongoDB connection is open.");
});

// Mongoose Schema definition
var Schema = mongoose.Schema;
var LocationSchema = new Schema({
    X: Number,
    Y: Number,
    Orientation: Number,
    UserID: String,
    Time: String
});

// Mongoose Model definition
var LocationsCollection = mongoose.model('locations', LocationSchema);

// create application/json parser
var jsonParser = bodyParser.json();

// URL management
app.get('/', function (req, res) {
    res.sendFile(__dirname + '/index.html');
});

app.post('/update', jsonParser, function (req, res) {
    if (!req.body) return res.sendStatus(400);
    else {
        console.log(req.body);
    }
});

// Start the server
var server = app.listen(3000, function () {
  var host = server.address().address
  var port = server.address().port
  console.log('App listening at %s:%s',host, port)
});

The key part is the app.post method which processes the incoming http request being sent from my iOS app. At the moment, the method which prints the req.body to the console looks like this:

{ 
  datapoint_1:
   { timestamp: '2015-02-06T13:02:40:361Z',
     x: 0.6164286615466197,
     y: -0.6234909703424794,
     id: 'B296DF8B-6489-420A-97B4-6F0F48052758',
     orientation: 271.3345946652066 },
  datapoint_2:
   { timestamp: '2015-02-06T13:02:40:961Z',
     x: 0.6164286615466197,
     y: -0.6234909703424794,
     id: 'B296DF8B-6489-420A-97B4-6F0F48052758',
     orientation: 273.6719055175781 }
}

So, you can see the request is a nested JSON object. Ideally, I'd like to loop through the request objects (ie. the datapoints) and insert those into the mongoDB database (via mongoose). However, I can't seem to figure out how to do much of anything with the req.body. I can't seem to create a loop to iterate through the request or how to properly parse the nested JSON file so it matches the mongoose schema. Can anyone provide some guidance on how to insert these datapoints into the mongoose database?


Source: (StackOverflow)

express body-parser middleware puts data into the property name

I'm new to the nodeJS Express framework. I'm consuming a POST request that I sent using the following:

router.post('/', function(req, res) {
    var data = Object.getOwnPropertyNames(req.body)[0];
});

I've sent this data from the client via:

$.ajax({
    url: "write_to_region",
    type: "POST",
    data: JSON.stringify(grid)
});

where "grid" is a 2d array of values. My express body parser is configured as follows:

app.use(bodyParser.urlencoded({limit: '50mb', extended: false }));

What is a better or more idiomatic way of doing this? Note that the array is somewhat large (10kb) and contains only integers. Ideally, I would be minimizing the amount of data sent in the request. Thanks!!


Source: (StackOverflow)

body-parser get empty body when content-type have multiple values

I upgrade from express 3 to 4, the body parse middleware has changed, so I use body-parser and it looks fine in most situation:

var bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

But I have a 3rd party service, which will call one of my specific url to notify messages, it works fine in express 3, but failed in express 4, because req.body is empty

I debug the request header, found that the Content-Type is application/x-www-form-urlencoded; text/html; charset=UTF-8 rather than application/x-www-form-urlencoded

so I tested in curl, when I remove text/html; charset=UTF-8, the req.body can show my post body exactly.

so what should I do then? it's 3rd party service, it's no reason for them to change their code, is there a node way? tks


Source: (StackOverflow)

body-parser node module returning a 'depricated' message [duplicate]

This question already has an answer here:

I'm in the process of learning Node.js - and in working thru some examples, Im using 'express' framework, and I've installed body-parser (using npm install body-parser) and it went fine... however when I start my app - Node shows this

body-parser deprecated bodyParser: use individual json/urlencoded middlewares: app.js:30:11
body-parser deprecated undefined extended: provide extended option: node_modules\body_parser\index.js:85:29

however it goes on to show its "normal" listening on port xxxx.

Of course, just learning - I don't have a ton of experience with packages, but I take the first line as 'express 4' not liking my version of body-parser - although I got it form the link on express' site.

http://expressjs.com/resources/middleware.html
https://github.com/expressjs/body-parser?_ga=1.200820398.1885847446.1420349783 

My app js looks like this at the moment - AND IT'S WORKING, so I'm not sure how to 'take' this message. (the line with " app.use( bodyParser() );" is line 30 reference above)

var express = require( 'express' );
var path = require( 'path' ); 
var bodyParser = require( 'body-parser' );

var app = express();

// configure app
app.set( 'view engine', 'ejs' );
app.set( 'views', path.join( __dirname, 'views' ) );

// use middleware
    // Body Parser for express
    app.use( bodyParser() ); // ****** this is line 30 referenced in the msg above *****


// ** NOTE this data is here for our learning scenario - but we'd normally be calling a persistentan datastore (such as a db) to get the data
var todoItems = [
         { id: 1, desc: 'one' }
        ,{ id: 2, desc: 'two' }
        ,{ id: 3, desc: 'three' }
    ];


// define routes
app.get( '/', function( req, res ) {
    res.render( 'index', {
        title: 'My 1st Node App'
    ,items: todoItems
    });
});

app.post( '/add', function( req, res ) {
    // handle the post data (need middleware (body_parser) to handle 'body'..express does not come with default )
    var newItem = req.body.newItem;

    //debug purposes
    console.log( newItem );

    // do something with the data - *NOTE: normally we'd put it to a persistent datastore
    todoItems.push({
         id: todoItems.length + 1
        ,desc: newItem
    });

    // redirect the user
    res.redirect( '/' );

});


app.listen( 1337, function() {
    console.log( 'ready on Port 1337.' );
});

And the index.js from the installed package of body-parser looks like this:

/*!
 * body-parser
 * Copyright(c) 2014 Douglas Christopher Wilson
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var deprecate = require('depd')('body-parser')
var fs = require('fs')
var path = require('path')

/**
 * @typedef Parsers
 * @type {function}
 * @property {function} json
 * @property {function} raw
 * @property {function} text
 * @property {function} urlencoded
 */

/**
 * Module exports.
 * @type {Parsers}
 */

exports = module.exports = deprecate.function(bodyParser,
    'bodyParser: use individual json/urlencoded middlewares')

/**
 * Path to the parser modules.
 */

var parsersDir = path.join(__dirname, 'lib', 'types')

/**
 * Auto-load bundled parsers with getters.
 */

fs.readdirSync(parsersDir).forEach(function onfilename(filename) {
    if (!/\.js$/.test(filename)) return

    var loc = path.resolve(parsersDir, filename)
    var mod
    var name = path.basename(filename, '.js')

    function load() {
        if (mod) {
            return mod
        }

        return mod = require(loc)
    }

    Object.defineProperty(exports, name, {
        configurable: true,
        enumerable: true,
        get: load
    })
})

/**
 * Create a middleware to parse json and urlencoded bodies.
 *
 * @param {object} [options]
 * @return {function}
 * @deprecated
 * @api public
 */

function bodyParser(options){
    var opts = {}

    options = options || {}

    // exclude type option
    for (var prop in options) {
        if ('type' !== prop) {
            opts[prop] = options[prop]
    }
    }

    var _urlencoded = exports.urlencoded(opts)
    var _json = exports.json(opts)

    return function bodyParser(req, res, next) {
        _json(req, res, function(err){
            if (err) return next(err);
            _urlencoded(req, res, next);
        });
    }
}

this appears on line 29 - and I have to assume this is the source of the message

exports = module.exports = deprecate.function(bodyParser, 'bodyParser: use individual json/urlencoded middlewares')

I don't understand the purpose though? As I said - things 'seem' to be working - With quite a few 'js warnings' in my console, but still.

I guess the question is. 1- is this type of message normal in node packages? 2- if not, what can be done 3- can someone familiar please give me some insight on where to find information.

Thank You.


Source: (StackOverflow)

What do nodes Body Parser and cookie parser do? And should I use them?

I have read all the documentation I can find, but I can not find a simple explanation of what these two middleware do.

What does the body in body-parser refer to? Why does the body need to be parsed?

Similarly for cookies. Am I correct that cookie-parser "parses" or beaks down the cookies that accompany a web user?

Lastly, I have read that body-parser is both unsafe and deprecated in Express4. Should I not use it?


Source: (StackOverflow)

Express4.10 bodyParser req.body undefined

I'm trying to build the login of a node application trying to access the route / login get: req.body undefined

Error:

TypeError: Cannot read property 'usuario' of undefined
   at login (/home/makros/workspace/ntalk/controllers/home.js:8:24)
   at Layer.handle [as handle_request] (/home/makros/workspace/ntalk/node_modules/express/lib/router/layer.js:82:5)
   at next (/home/makros/workspace/ntalk/node_modules/express/lib/router/route.js:100:13)
   at Route.dispatch (/home/makros/workspace/ntalk/node_modules/express/lib/router/route.js:81:3)
   at Layer.handle [as handle_request] (/home/makros/workspace/ntalk/node_modules/express/lib/router/layer.js:82:5)
   at /home/makros/workspace/ntalk/node_modules/express/lib/router/index.js:235:24
   at Function.proto.process_params (/home/makros/workspace/ntalk/node_modules/express/lib/router/index.js:313:12)
   at /home/makros/workspace/ntalk/node_modules/express/lib/router/index.js:229:12
   at Function.match_layer (/home/makros/workspace/ntalk/node_modules/express/lib/router/index.js:296:3)
   at next (/home/makros/workspace/ntalk/node_modules/express/lib/router/index.js:190:10)

app.js

var express = require('express'),
load = require('express-load'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
bodyParser = require('body-parser'),
app = express();


load('models')
    .then('controllers')
    .then('routes')
    .into(app);

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.use(cookieParser('secret'));
app.use(session({
    secret: 'secret', 
    resave: true, 
    saveUninitialized: true
}));

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(express.static(__dirname + '/public'));

app.listen(3000,function(){
    console.log('Started!');
});

package.json

{
  "name": "ntalk",
  "version": "1.0.0",
  "private": true,
  "scripts": {
  "start": "node ./bin/www"
  },
  "dependencies": {
  "body-parser": "^1.9.0",
  "cookie-parser": "^1.3.3",
  "ejs": "~0.8.5",
  "express": ">= 0.0.0",
  "express-load": "^1.1.14",
  "express-session": "^1.8.2"
  }
}

controllers/home.js

module.exports = function(app) {
    return {
        index: function(req, res) {
            res.render('home/index');
        },
        login: function(req, res){
            console.log(req.params);
            var email = req.body.usuario.email,
                nome = req.body.usuario.nome;
            if(email && nome) {
                var usuario = req.body.usuario;
                usuario['contatos'] = [];
                req.session.usuario = usuario;
                res.redirect('/contatos');
            } else {
                res.redirect('/');
            }
        },
        logout: function(req, res){
            req.session.destroy();
            res.redirect('/');
        }
    };
};

routes/home.js

module.exports = function(app) {
    var home = app.controllers.home;    
    app.get('/', home.index);
    app.get ('/entrar', home.login);
    app.get('/sair', home.logout);
};

views/home/index.ejs

<% include ../header %>
        <header>
            <h1>Ntalk</h1>
            <h4>Bem-vindo!</h4>
        </header>
        <section>
            <form action="/entrar" method="post">
                <input type="text" name="usuario[nome]" placeholder="Seu nome">
                <br>
                <input type="text" name="usuario[email]" placeholder="Seu e-mail">
                <br>
                <button type="submit">Entrar</button>
            </form>
        </section>
<% include ../footer %>

Please help me!


Source: (StackOverflow)

how to handle body-parser errors in express nodejs

I am hitting a web service on Node with following data,

MY request data is:

{
"first_name":"surinder",,
"last_name":"rawat",
"email":"surinder.rawat@testcompany.com",
"phone":"1234567890",
"password":"surinder",
"user_type":"H",
"device_type":"A"
}

and getting following error:

Connect
400 SyntaxError: Unexpected token ,
   at Object.parse (native)
   at parse (/home/surinder/workspace/HappyHakka/node_modules/body-parser/lib/typs
   /json.js:76:17)
   at /home/surinder/workspace/HappyHakka/node_modules/body-parser/lib/read.js:98:18
   at IncomingMessage.onEnd (/home/surinder/workspace/HappyHakka/node_modules/body-parser
   /node_modules/raw-body/index.js:136:7)
   at IncomingMessage.g (events.js:180:16)
   at IncomingMessage.emit (events.js:92:17)
   at _stream_readable.js:943:16
   at process._tickCallback (node.js:419:13)

I intentionally used double comma to get this error. I want to know how to handle this error and show user an error in a proper format

Thanks


Source: (StackOverflow)

Express js - request body is empty

I just installed the latest versions of modules. I can not get any GET or POST variables. What i do wrong? NODE: v0.12.2

var express        =         require("express");
var bodyParser     =         require("body-parser");
var app            =         express();
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res) {
    res.setHeader('Content-Type', 'text/plain')
    res.write('you posted:\n')
    res.end(JSON.stringify(req.body, null, 2))
});
app.listen(3000,function(){
    console.log("Started on PORT 3000");
})

http://localhost:3000/?token=devvvvv GET returns: you posted: {}

Thanks for answers, but problem with POST does not solved... POST token=as123ds on http://localhost:3000/ return empty array in req.body How can i solve this?


Source: (StackOverflow)

Body-parse in Node.js not escaping new line chars in request body ? JSON

I am creating a basic reverse proxy to pass on client requests to a remote server.

So I used body-parse with express.js for Node server to allow me to pass on the body.

However the JSON contains new line characters in it and extra braces.

Client Side

{
   "lastRefreshedDateTime" : "2015-05-24",
   "uid" : "1232141451"
}

Server Side

{
    '{
        \r\n"lastRefreshedDateTime": "2015-05-24",
        \r\n"uid
": "1234567124321"\r\n
    }\r\n': ''
}

Node.js code

        var express = require('express');
    var http = require('request');
    var path = require('path');
    var url = require("url");
    var bodyParser = require("body-parser"); //this is required in express 4.x to output the contents of the client request body
    var app = express(); //start express server

    // parse application/x-www-form-urlencoded
//app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser().json())
    // POST - getLocationData
    app.post('/getLocationData', function (request, response)
    {
        console.log("Request for /getLocationData");
        forwardRequest(request, response, "getLocationData", "POST", true);
    });


    app.listen(8080);

    function forwardRequest(request, response, serviceName, requestMethod, isJSON)
    {

        console.log("Making request to EAS for " + serviceName + ":");
        console.log(request.body); //json is fubar!

    };

I have tried removing the new line characters myself, but it still doesnt solve the problem of the additional braces and inverted commans


Source: (StackOverflow)

json request body parse

"name": "body-parser", "version": "1.13.3",

my json request body is{user:'guow'} , but express request.body is { '{user:\'guow\'}': '' }

This is configuration of my express app

var bodyParser = require('body-parser'); //
var multer = require('multer');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: false })); // for parsing application/x-www-form-urlencoded //
app.use(multer());

I am sending request with jquery and my code is

$.ajax({ type: “POST”, url: “/login”, cache: false, dataType: 'json', data:“{user:'guow'}"});

Will someone encountered such a problem?


Source: (StackOverflow)

Node get posted variables via body-parser

I'm trying to retrieve the posted variables in a node application. I'm using Postman form-data (like I have in so many other API testing situations) to post a message to my node application. But when I console.log the request.body, I get an empty object. Here is my entire node app:

var express = require('express');
var app = express();
var bodyParser = require("body-parser");

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.post('/foo',function(request,response){
    console.log(request.body);
});


app.listen(3000, function(){
  console.log('listening on *:3000');
});

After posting some data, here is what shows in my console:

listening on *:3000
{}

Here is my package.json:

{
  "name": "api",
  "version": "0.0.1",
  "description": "api",
  "dependencies": {
    "express": "^4.12.4",
    "socket.io": "^1.3.5",
    "body-parser": "~1.12.0"
  }
}

I think I'd like to continue to use body parser because I plan on making this an API with json data. The app loads up just fine with no errors. What am I missing?


Source: (StackOverflow)