Gary Kipnis Gary Kipnis - 8 months ago 45
JSON Question

Node.js Express3 to Express4 migration - parser usage

My Node based server uses Express. The server handles json only routes and file upload routes which use multi-part forms. When using Express3, the built in parser was parsing both kinds of routes. I am in the process of migrating to Express4. The body-parser, that I had to switch for Express4, only parses jsons. I am using multer parser to parse file uploads.

For each route, I am specifying which parser to use, as in:

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

var jsonParser = bodyParser.json();
var upload = multer({dest : 'upload/' });
var uploadParser = upload.any();
var app = express();

// json route handling'json_only_route', jsonParser, function(req, res) {...});

// upload route handling'upload_route', uploadParser, function(req, res) {...});

Alternatively, for json only parsing, I could use the multer parser as well, as below:

var jsonParserMulter = uploadParser.none();

// json route handling'json_only_route', jsonParserMulter, function(req, res) {...});

Are there any reasons to use one approach over the other? Would 'body-parser' offer better performance for json only parsing?


It looks like multer doesn't support JSON. By using uploadParser.none() it will just pass through the JSON as a string. Express' bodyParser.json() is the way to go if you want to parse the JSON string into an object.