简体   繁体   English

带有Express API的multer和body-parser的req.file未定义

[英]req.file undefined for multer and body-parser with express API

I'm writing an API that will have to deal with uploading files along with other GET, POST requests. 我正在编写一个API,该API必须处理上传文件以及其他GET,POST请求。 I attempting to handle a file upload with multer , and use body-parser for any other HTTP Request. 我尝试使用multer处理文件上传,并将body-parser用于其他任何HTTP请求。 For any uploads I like to use the endpoint '/api/upload' which will utilize multer, and any other API call will used a route defined in api.js , which is also '/api' but for many other functions. 对于任何上载,我喜欢使用端点“ / api / upload”,该端点将使用multer,并且任何其他API调用都将使用api.js定义的api.js ,该路由也是“ / api”,但还有许多其他功能。 Here is part of my server.js file that is setting up the server and routes: 这是我的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' ) );
});

...

I'm storing all of my routes inside two different files: upload.js and api.js . 我将所有路线都存储在两个不同的文件中: upload.jsapi.js api.js will house all the related functions that can use the body-parser for the request body, while upload.js will use multer to process any file uploads. api.js将容纳所有可用于请求正文的body-parser的相关功能,而upload.js将使用multer处理任何文件上传。

Here is my api.js file: 这是我的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;

and my upload.js file: 和我的upload.js文件:

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

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

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

module.exports = router;

The controller entity.controller.js contains all the API functions to process these calls. 控制器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 ) 
{
....
};

I'm attempting to test my API by performing a POST request through Postman. 我正在尝试通过邮递员执行POST请求来测试我的API。 Here is a snapshot of my request being sent: 这是我的请求被发送的快照: 邮递员POST请求

However, every time I check req.file inside of exports.upload it always returns undefined . 然而,每次我检查req.file里面的exports.upload它总是返回undefined I've seen other posts on stackoverflow, but they seemed to mostly be sticking with one middleware to parse the incoming request, where as I like to use body-parser for certain requests and multer for others involving file uploads. 我曾在stackoverflow上看到过其他文章,但它们似乎主要是坚持使用一种中间件来解析传入的请求,就像我喜欢对某些请求使用body-parser并针对涉及文件上传的其他请求使用multer Is this possible, and based off my current setup what could I be doing wrong? 这是否可能,并且根据当前设置,我可能会做错什么? Also though, if this is convoluted and unnecessary and if it would be better to stick with one parser then going between the two that works too. 同样,如果这很麻烦并且不必要,并且最好坚持使用一个解析器,那么在两个解析器之间也可以工作。

Thanks! 谢谢!

You need to modify your code like this to work: 您需要像这样修改代码才能工作:

server.js server.js

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

entity.controller.js 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."
        });
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM