Azure Node.js Easy API中间件

时间:2018-09-11 08:18:06

标签: node.js azure express azure-mobile-services

我有一个Azure node.js应用程序。我只想在一个POST easy-api中添加用于文件上传的“ multer”中间件。

例如,我有一个文件./api/upload-files.js,看起来应该像这样:

module.exports = {
    "post" : async (req, res, next) => {
        // ...
    }
};

我可以很容易地将multer中间件添加到./app.js文件中,其中快递应用程序已初始化:

const multer = require('multer');
app.post('*', multer({ storage: multer.memoryStorage() }).any());

但是,如果我不想将multer中间件添加到每个端点,而只是添加到./api/upload-files.js中的那个中间件,我该怎么做?

1 个答案:

答案 0 :(得分:0)

原始评论

这与您在应用中实例化Express实例的方式有关。

如果您不希望对某些请求使用multer中间件,则可以只在请求本身中使用所需的函数,避免将参数传递给request方法时调用multer函数。

获取端点的一个示例:

app.get('/getrequest', (req, res, next) => {
    console.log('Someone made a get request to your app');
})

发布端点的一个示例:

app.post('/postrequest', (req, res, next) => {
    console.log('Someone made a POST request to your app');
})

请记住,您以这种方式添加或删除中间件功能。

app.use('/user/:id', function (req, res, next) {
  console.log('I am a middleware!')
  next()
}, function (req, res, next) {
  console.log('I am another function')
  next()
})

Here are the docs

编辑

也许此代码可以适应您的用例?

app.post('*', checkUseMulter);

function checkUseMulter(req, res, next) {
    if (['/mypathwithoutmulter', '/myotherpath'].includes(req.path)) {
        return next();
    }

    return multer({ storage: multer.memoryStorage() }).any();
}