无法 POST 使用节点和 Express(Jade、MongoDB、Express、Node)

Cannot POST using node & Express (Jade, MongoDB, Express, Node)

我有一个表单,用户可以在其中 select .xlsx 文件并上传它:

      p Upload New Schedule
      #uploadNew
        form(id = "form1", action="/uploadNew", method="post", enctype="multipart/form-data")
          input(type="file", id="control", name="XLupload")
          br
          input(type="submit" value="Upload" name="Submit")

在我的主app.js中我有这个路由来处理。

var uploads = require('./routes/upload');
//Make the db accessible to various http requests
app.use(function(req, res, next) {
  req.db = dbMain;
  next();
});
app.use('/', routes);
app.use('/upload', uploads);

并且在我的 upload.js 文件中我有以下内容:

var xlsx = require('xlsx');
var multer = require('multer');
var upload = multer({dest: './uploads'});
var excel_upload = upload.single('XLupload');

router.get('/upload', stormpath.groupsRequired(['Enforced']), function(req, res) {
    res.render('upload', {
        title: 'Uploading Excel File'
    });
    next();
});

router.post('/upload', excel_upload, function(req, res) {
    // Get the path to the uploaded Excel file
    var fileObject = req.file;
    var filePath = fileObject.path;

    // Get collection instance which will store the data from the newly posted schedule
    var dbLocal = req.db;
    var insertionCollection = dbLocal.collection('chip');
    .....

但是,当我启动并在本地主机上侦听时,当我 select 一个文件并尝试上传时,我收到错误无法 POST /upload。当我没有路由并且所有内容都在主 app.js 文件中时,这不是问题。我引入路由搞砸了什么?

这个:

app.use('/upload', uploads);

结合这个:

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

声明这条路线:POST /upload/upload

如果您挂载一个路由器(使用app.use(PATH, router)),PATH会为该路由器处理的所有路由添加一个前缀。您的路由器需要声明相对于该前缀的路由:

router.post('/', ...)