类型错误:app.use()需要中间件

时间:2016-12-19 08:59:03

标签: javascript express multer

我无法弄清楚为什么会收到此错误。

当我尝试运行node filename.js时,我在控制台上遇到了类型错误:

  

app.use()需要中间件功能

我希望结果是:

  

使用端口3000

以下是我的代码:

var express = require('express');
var multer = require('multer');
var fs = require('fs');
var app = express();
var DIR = './uploads/';
var upload = multer({dest: DIR});

app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', 'http://valor-software.github.io');
  res.setHeader('Access-Control-Allow-Methods', 'POST');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
  res.setHeader('Access-Control-Allow-Credentials', true);
  next();
});

app.use(multer({
  dest: DIR,
  rename: function (fieldname, filename) {
    return filename + Date.now();
  },
  onFileUploadStart: function (file) {
    console.log(file.originalname + ' is starting ...');
  },
  onFileUploadComplete: function (file) {
    console.log(file.fieldname + ' uploaded to  ' + file.path);
  }
}));

app.get('/api', function (req, res) {
  res.end('file catcher example');
});

app.post('/api', function (req, res) {
  upload(req, res, function (err) {
    if (err) {
      return res.end(err.toString());
    }
    res.end('File is uploaded');
  });
});

var PORT = process.env.PORT || 3000;

app.listen(PORT, function () {
  console.log('Working on port ' + PORT);
});

1 个答案:

答案 0 :(得分:2)

根据n document of multer。您不能直接将multer对象作为参数传递。您应该通过调用成员函数来传递它们,例如single()field()array()

例如:

upload = multer({
  dest: DIR,
  rename: function (fieldname, filename) {
    return filename + Date.now();
  },
  onFileUploadStart: function (file) {
    console.log(file.originalname + ' is starting ...');
  },
  onFileUploadComplete: function (file) {
    console.log(file.fieldname + ' uploaded to  ' + file.path);
  }
})

app.use(upload.single(...));
app.use(upload.array(...));
app.use(upload.fields(...));
app.use(upload.any());