具有JSON和二进制数据传递功能的Express Body Parser [英] Express Body Parser with both JSON and binary data passing capability

查看:107
本文介绍了具有JSON和二进制数据传递功能的Express Body Parser的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Express应用路由器中,我已路由了一些请求,以接受JSON数据以及二进制数据的POST请求.问题是当我使用正文解析器传递JSON数据时,它还将二进制数据视为JSON并在发布二进制数据时给出错误.即当我使用时:

In my express app router, I've routes for accepting POST request of JSON data as well as binary data. The problem is when I use body parser for passing JSON data, it also considers the binary data as JSON and gives error while POSTing binary data. i.e. when I use:

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

当我删除它时,它仅适用于二进制数据.以下是我发布二进制文件的路线.

And When I remove this, It only works for binary data. Following is my route for POSTing binary file.

router.post('/file', function (req, res) {
    var gridfs = app.get('gridfs');
    var writeStream = gridfs.createWriteStream({
        filename: 'file_name_here'
    });
    writeStream.on('close', function (file) {
        res.send(`File has been uploaded ${file._id}`);
    });
    req.pipe(writeStream);
});

我也尝试过将此文件路由移动到其他路由器.在那种情况下,当我对body解析器不做任何设置时,它仍然会给出相同的错误.

I've also tried moving this file route to other router. In that case, when I don't set anything regarding body parser, it still gives the same error.

一个可以正常工作的修复方法是,在设置正文解析器之前将此文件路由放置在我的主 app.js 中.但是我认为这不是一个好方法.我希望这些路由位于单独的文件中.

One fix that works correctly is placing this file route in my main app.js prior to setting body parser. But I think this would not be good approach. I want these routes to be in separate files.

那么我在这里想念的是什么?任何替代方案也将不胜感激.

So what I'm missing here? Any alternatives will also be appreciated.

编辑

按照答案,我首先分离出需要正文解析的路由器,而不需要正文解析的路由器.还从我的主 app.use()中删除了bodu解析器.现在,在其中需要主体解析器的路由器中,我添加了这两行.但是行为是一样的.

As per the answer, I've first separated out my routers which requires body parsing and which do not. Also removed the bodu parser from my main app.use() Now in the router in which, I need body parser, I've added those 2 lines. But the behavior is same.

当我添加这两行时,仅JSON reqquest有效,而当我删除时,仅二进制POST req.作品.

When I add those 2 lines, only JSON reqquest works and when I remove, only binary POST req. works.

这是我更新的代码:

app.js

    const express = require('express');
const app = module.exports = express();
const bodyParser = require('body-parser');

const port = 8080;


// //parsing incoming requests using body-parser middlewares
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({ extended: false}));


//adding routes
app.use(require('./routes/additionRouter'));
app.use(require('./routes/mediaRouter'));

//catch 404 file not found here
app.use((req, res, next) => {
    const err = new Error('Page Not Found');
    err.status = 404;
    next(err);
});

//Error Handler
app.use((err, req, res, next) => {
    res.status(err.status || 500);
    res.send(err.message);
});

app.listen(port, () => {console.log('Server listening on port: ' + port)});

additionRouter.js

const express = require('express');
const router = express.Router();

var exported = require('../config/dbConnection');

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

 // parsing incoming requests using body-parser middlewares
 router.use(bodyParser.json());
 router.use(bodyParser.urlencoded({ extended: false}));

//Endpoint for adding new challenge
router.post('/endpoint1', (req, res, next) => {

});

module.exports = router; 

mediaRouter.js

    const express = require('express');
const mediaRouter = express.Router();
const exported = require('../config/dbConnection');

exported.cb((gridfs) => {
    //For adding media files to database named 'mediadb'
    //POST http://localhost:8080/file
    mediaRouter.post('/file', function (req, res) {
        // var gridfs = app.get('gridfs');
        var writeStream = gridfs.createWriteStream({
            filename: 'file_name_here'
        });
        writeStream.on('close', function (file) {
            res.send(`File has been uploaded ${file._id}`);
        });
        req.pipe(writeStream);
    });

    //GET http://localhost:8080/file/[mongo_id_of_file_here]
    mediaRouter.get('/file/:fileId', function (req, res) {
        // var gridfs = app.get('gridfs');
        gridfs.createReadStream({
            _id: req.params.fileId // or provide filename: 'file_name_here'
        }).pipe(res);
    });

});


module.exports = mediaRouter;

推荐答案

通过指定

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

您的整个应用程序都使用主体解析器中间件.您可以创建另一个中间件来处理是否使用主体解析器.例如:

your entire app uses the body parser middleware. You could create another middleware to handle whether or not the body parser is used. For example:

const bodyParse = bodyParser.json();
app.use((req, res, next) => {
    if(req.originalUrl == "restOfUrl/file") next();
    else bodyParse(req, res, next);
});

这篇关于具有JSON和二进制数据传递功能的Express Body Parser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆