【问题标题】:req.file undefined for multer and body-parser with express APIreq.file 未定义用于具有 express API 的 multer 和 body-parser
【发布时间】:2018-03-28 19:53:45
【问题描述】:

我正在编写一个 API,它必须处理上传文件以及其他 GET、POST 请求。我尝试使用multer 处理文件上传,并将body-parser 用于任何其他HTTP 请求。对于任何上传,我喜欢使用端点“/api/upload”,它将利用 multer,任何其他 API 调用将使用在api.js 中定义的路由,这也是“/api”,但用于许多其他功能。这是我的server.js 文件的一部分,用于设置服务器和路由:

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

const multer = require( 'multer' );
const upload = multer( { dest : '/uploads' } );

// create express app
const app = express();


// parse requests of content-type - application/x-www-form-urlencoded
app.use( bodyParser.urlencoded( { extended: true } ) );

// parse requests of content-type - application/json
app.use( bodyParser.json() );

...

const api_uploads = require( './server/routes/upload' );

app.use( '/api/upload', api_uploads );

// get API routes
const api = require( './server/routes/api' );

// set our api routes
app.use( '/api', api );


// catch all other routes and return the index file
app.get( '*', ( req, res ) =>
{
    res.sendFile( path.join( __dirname, 'dist/index.html' ) );
});

...

我将所有路线存储在两个不同的文件中:upload.jsapi.jsapi.js 将包含所有可以使用body-parser 作为请求正文的相关函数,而upload.js 将使用multer 来处理任何文件上传。

这是我的api.js 文件:

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

const entities = require( '../controllers/entity.controller.js' );

// default api listing
router.get('/', function(req, res) 
{
res.send('api works');

});

// Retrieve all Entities
router.get( '/', entities.findAll );

// Create a new Entity
router.post( '/', entities.create );

// search for entities
router.get( '/search', entities.find );

// download all available entities
router.get( '/download', entities.downloadAll );

// download specific entities
router.post( '/download', entities.download );

// Delete an Entity with entityId
router.delete( '/:entityId', entities.delete );

module.exports = router;

还有我的upload.js 文件:

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

const entities = require( '../controllers/entity.controller.js' );

router.post( '/', entities.upload );

module.exports = router;

控制器entity.controller.js 包含处理这些调用的所有API 函数。

var Entity = require( '../models/entity.model.js' );

const multer = require( 'multer' );
const upload = multer( { dest : '/uploads' } );

exports.findAll = function( req, res ) 
{
....
};

exports.create = function( req, res ) 
{
....
};

exports.find = function( req, res )
{
....
}

exports.downloadAll = function( req, res )
{
....
}

exports.download = function( req, res)
{
....
}

exports.upload = ( upload.single( 'entity' ), function( req, res )
{
    if( req.file )
    {
        console.log( 'file send successfully' );
        res.send( { message : 'thank you for the file' } );
    }
    else
    {
        res.status( 500 ).send( { message: "Some error occurred while acquiring file." } );
    }       
});

exports.delete = function( req, res ) 
{
....
};

我正在尝试通过 Postman 执行 POST 请求来测试我的 API。这是我发送请求的快照:

但是,每次我在exports.upload 中检查req.file 时,它总是返回undefined。我在 stackoverflow 上看过其他帖子,但他们似乎大多坚持使用一个中间件来解析传入的请求,因为我喜欢使用 body-parser 处理某些请求,而使用 multer 处理其他涉及文件上传的请求。这可能吗,根据我目前的设置,我可能做错了什么?不过,如果这是令人费解且不必要的,并且如果坚持使用一个解析器会更好,那么在两者之间进行也可以。

谢谢!

【问题讨论】:

    标签: javascript node.js express multer body-parser


    【解决方案1】:

    你需要像这样修改你的代码才能工作:

    server.js

    app.use( '/api/upload', upload.single('entity'), api_uploads );
    

    entity.controller.js

    exports.upload = function (req, res) {
        if (req.file) {
            console.log('file send successfully');
            res.send({
                message: 'thank you for the file'
            });
        } else {
            res.status(500).send({
                message: "Some error occurred while acquiring file."
            });
        }
    };
    

    【讨论】:

    • 我在设置路由之前重新安排了代码做app.use( bodyParser...,但它仍然抛出一个错误,说req.file未定义。
    • 不幸的是也未定义。我实际上注释掉了为/api 设置路由的行,并使用upload.js 中定义的路由来查看是否只使用该文件,但它仍然说它是未定义的。
    • 我已更新我的帖子以包含我对 API 的请求的图像。我正在使用 Postman 并点击 /api/entities/upload 端点来上传文件。
    • 啊,我明白了,这似乎是一个奇怪的问题,它必须在 server.js 文件中才能正确运行,并且不能是另一个文件中指定的路由?如果您更新您的帖子,我可以将其标记为已回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 2020-12-17
    • 2018-08-06
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    相关资源
    最近更新 更多