无法使用节点& Express(Jade,MongoDB,Express,Node)

时间:2015-08-06 06:12:21

标签: node.js post express pug

我有一个表单,用户可以在其中选择.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');
    .....

但是,当我启动并在localhost上监听时,当我选择一个文件并尝试上传时,我得到的错误无法POST /上传。当我没有路由并且在app.js主文件中包含所有内容时,这不是问题。通过引入路线我搞砸了什么?

1 个答案:

答案 0 :(得分:2)

此:

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

结合这个:

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

声明此路线:POST /upload/upload

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

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