restify 2.6.1 how to disable body parser for specific request

巧了我就是萌 提交于 2020-01-01 03:25:30

问题


I am pretty new to node.js services and I am facing a problem with multipart/form-data content type. I need a way to disable body parser functionality for specific request. I am using restify 2.6.1. Below are some snippet of the configuration.

My setup is:

    App.js :

    server.use(restify.authorizationParser());
    server.use(restify.dateParser());
    server.use(restify.queryParser());
    server.use(restify.jsonp());

    server.use(restify.bodyParser());
    server.use(restifyValidator);
    server.use(restify.gzipResponse());
    server.use(passport.initialize());
    server.use(restify.conditionalRequest());


Route.js : 
       app.post({path: '/test/upload/:upload_image_name', version: ver}, uploadCtr.uploadImage);
       app.post( {path: '/test/upload/:upload_image_name', version:ver }, passport.authenticate('bearer',{ session: false}),uploadCtr.uploadImage);

Without restify.bodyParser() the upload image is working( but everything which is relying on the json parser is failing )

Thanks in advance.


回答1:


You shouldn't use bodyParser() for every route by default. In fact, you should only use bodyParser() for routes that require multipart uploads.

All servers using express.bodyParser are vulnerable to an attack which creates an unlimited number of temp files on the server, potentially filling up all the disk space, which is likely to cause the server to hang.

Demonstration

This problem is extremely easy to demonstrate. Here's a simple express app:

var express = require('express');
var app = express();

app.use(express.bodyParser());
app.post('/test', function(req, resp) {
  resp.send('ok');
});

app.listen(9001);

Seems pretty innocuous right?

Now check how many temp files you have with something like this:

$ ls /tmp | wc -l
33

Next simulate uploading a multipart form:

$ curl -X POST -F foo=@tmp/somefile.c http://localhost:9001/test
ok

Go back and check our temp file count:

$ ls /tmp | wc -l
34

That's a problem.

http://andrewkelley.me/post/do-not-use-bodyparser-with-express-js.html

This problem also exists with Restify.

You can solve the problem by replacing .bodyParser() with:

server.use( restify.queryParser() );
server.use( restify.jsonBodyParser() );

But to answer your question about a particular route, you should move any middleware that you don't need for all routes into route specific middleware:

server.get('/route', restify.queryParser(), restify.jsonBodyParser(), routeHandler);

This can also take an array:

var routeMiddleware = [
      restify.queryParser(),
      restify.jsonBodyParser()
    ];

server.get('/route', routeMiddleware, routeHandler);


来源:https://stackoverflow.com/questions/21498856/restify-2-6-1-how-to-disable-body-parser-for-specific-request

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!