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

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?

You can supply middleware to a single route by doing this:
var multipartyMiddleware = function (req,res,next){
//put your code to parse multipart here and call "next" when done
}
app.post('/this/is/a/single/route', multipartyMiddleware, function(req,res){
//do normal business logic in this route and send the response
})
If you need to bypass the multipart parsing in the old bodyParser in express 3 you can replace this:
app.use(express.bodyParser())
with this:
app.use(express.json())
app.use(express.urlencoded())
This works because the source of the bodyParser middleware reveals that it is just a combo of three middleware parsers: multipart, json, and urlencoded.
see the connect 2.X source here: https://github.com/senchalabs/connect/blob/2.x/lib/middleware/bodyParser.js#L54

Related

How to inject a request (bypass HTTP protocol stack) in nodejs express?

Imagine this sample Express app straight from the documentation:
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(3000)
What is the idiomatic way to invoke the '/' endpoint programmatically from a different point in the same application code? Assume that I already removed the last line app.listen(3000).
The reason for this is that I want to take something like express-pouchdb and write an adapter for a different wire protocol, but leveraging the extensive routes already defined. I want to invoke these routes directly from js code without going over the network.
The application has dozens of routes already defined so changing each one to direct function calls as suggested in the first comment is not an option.
UPDATE:
I tried calling app.route.dispatch() but nothing comes back on the rsp object.
Your question is a duplicate of this answer: Is it possible to call Express Router directly from code with a "fake" request?
You can use run-middleware module exactly for that. You create an express app a usual, and then you can call the app using your parameters

difference between app.use('/users', usersRouter); and require(./routes/users)(app)?

In the express tutorial from mozilla,
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website
they write
var usersRouter = require('./routes/users');
app.use('/users', usersRouter);
In other tutorials, they write something like this,
require('./routes/authRoutes')(app);
Are the two pretty much equivalent?
Without seeing the code for the other tutorials that you mentioned I cannot be sure exactly how they consume the app object that is passed to the imported code, but I suspect that whatever code is implemented in the .routes/authRoutes module simply connects a router object to the specified app object. This would most likely be done in the same way as the code that you provided from the Mozilla Express tutorial.
In both cases, a route handler is being defined and then registered as a handler for any routes that match the specified route. In the case that you mentioned that route would be the /users route. So the usersRouter object would have a number of route handlers defined, for example, for routes /abc and /def. So registering the usersRouter object as a route handler for the /users route would mean that the routes /users/abc and /users/def would be handled.

Using Express and Body-Parser in a Google Cloud Function (NOT Firebase Cloud Function)

I am trying to get my head around using GCF and Express together. All of the examples I have found give good info about Firebase CF but not straight up GCF.
Specifically, I need to use body-parser to get at some POSTed body info that is being sent via a content-type of 'x-www-form-urlencoded' rather than 'application/json'. I can see the data if I console.log the req.rawBody but haven't found a clean way to get at the body parts.
I found this article: https://mhaligowski.github.io/blog/2017/05/15/serving-functions-express.html but to me it is just a couple of code snippets that really isn't clear on how things actually hang together.
You can require body-parser and as long as you send the Content-Type: application/json header, it will parse as JSON automatically:
const bodyParser = require('body-parser');
exports.acceptJson = (req, res) => {
console.log(req.body);
res.status(200);
};

Express JS modules to parse form-data text from Postman

I have just 3 variables and posting using postman to sever.
I need a solution to parse just form-data text in Express JS
When I searched in net, I see people just suggested that,
We cant use body-parser to handle form-data and need to use multer, busboy, multiparty
Also people suggest if not sending files need not use multer and formidable.
But can anyone explain how exactly to use this with node js. When I see modules github, i am not able to understand to use it for my needs.
https://stackoverflow.com/a/36199881/5078763
I know setting x-www-form-urlencoded option in postman works but I need for form-data
app.post('/addUsrForm', addUsrFnc);
function addUsrFnc(req, res)
{
console.log("Data Received : ");
var namUserVar =
{
nameKey: req.body.nameKey,
mailKey: req.body.mailKey,
mobileKey: req.body.mobileKey
};
console.log(NquUsrJsnObjVar);
}
This answer provides good detailing of the different use cases for html form encoding. What does enctype='multipart/form-data' mean?
x-www-form-urlencoded is the default.
multipart/form-data is for larger data sends, such as entire files.
Postman settings aside, if your server needs to handle multipart/form-data, install multer and use it like so...
if just sending text fields in a multipart/form-data encoding:
var multer = require('multer')
var multParse = multer()
...
function handler(req, res) {
// fields will be parsed in req.body
}
...
app.post('/', multParse.none(), handler)
Follow the multer api on the multer github page if you actually are sending files and not just text fields.

Unobtrusive middle-ware for Expres.js to inspect request body

Does there exist a thirdparty middleware or a way to create such middleware for Express.js that allows for intercepting all requests and inspecting the request's body content without affecting subsequent middleware such as bodyParser or route endpoints which may rely on the raw body such as express-http-proxy?
From what I can tell bodyParser itself seems to work in a somewhat obtrusive way that does not allow a route to override the default parsing behavior. The express documentation describes how request.body is filled in by middleware such as bodyParser. This behavior of bodyParser makes sense from simplicity and performance perspective but doesn't make it a great candidate for creating middleware which needs to inspect the contents of a request and let the remaining portion of the app working without modification. This is especially true seeing that depending on the parsing middleware the results may be in entirely different formats. After some digging I'm left wondering if it's generally possible to pull this off with express or perhaps once you read the request body you eliminate the ability to make use of further middleware such as bodyParser or express-http-proxy which expect to access the body directly.
Possibly related:
express req.pipe() does not work
You could always use the raw-body package with express middleware like so:
var getRawBody = require('raw-body');
var typer = require('media-typer');
app.use(function (req, res, next) {
getRawBody(req, {
length: req.headers['content-length'],
limit: '1mb',
encoding: typer.parse(req.headers['content-type']).parameters.charset
}, function (err, string) {
if (err) return next(err)
req.text = string
next()
})
})
If your only concern is performance, I wouldn't worry too much about body-parser as it's unlikely to have a massive performance impact. If you can, I'd suggest you just use body-parser with a typical express middleware app.use(..) to inspect the request body.