简体   繁体   中英

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. I attempting to handle a file upload with multer , and use body-parser for any other HTTP Request. 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. Here is part of my server.js file that is setting up the server and routes:

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 . 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.

Here is my api.js file:

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:

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.

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. 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 . 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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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