使用快速API

时间:2018-03-28 19:53:45

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

我正在编写一个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 ) 
{
....
};

我正在尝试通过邮递员执行POST请求来测试我的API。以下是我发送的请求的快照:postman POST request

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

谢谢!

1 个答案:

答案 0 :(得分:0)

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

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