NodeJS发布请求“无法发布/上传”

时间:2018-08-19 07:39:31

标签: javascript html node.js express router

我正在尝试在NodeJS中创建的Web应用程序上做一个简单的上传功能。我有一个/ admin路由,用于呈现表单页面。下面是/admin.handlebars页面的HTML。

<body>
  <div class = "container">
    <div class = "row">
      <div class = "col-md-6 m-auto">
        <h1 class = "text-center display-4 my-4">Upload Tutorial Template</h1>
        <form action = "./upload" method ="POST" enctype="multipart/form-data">
          <div class="custom-file mb-3">
            <input type="file" name="file" id="file" class="custom-file-input">
            <label for = "file" class="custom-file-label">Choose Video</label>
            </div
        </form>
        <input type="submit" value="Submit" class="btn btn-primary btn-block"
      </div>
    </div>
  </div>`

下面显示了admin.js文件中用于处理发布请求的部分,当前我正在尝试在屏幕上呈现文件名,但是当我单击sumbmit按钮时,屏幕显示“无法发布/上传”。

router.get('/', function (req, res) {
  console.log("Rendered Upload page")
  res.render('admin');
});

//route of post to upoad, Uploads file to db
router.post('/upload', upload.single('file'), function (req, res) {
  console.log("Post made")
  res.response({file: req.file});
});

编辑,还包含主app.js文件。

 var express = require('express');
 var path = require('path');
 var cookieParser = require('cookie-parser');
 var bodyParser = require('body-parser');
 var exphbs = require('express-handlebars');
 var expressValidator = require('express-validator');
 var flash = require('connect-flash');
 var session = require('express-session');
 var passport = require('passport');
 var LocalStrategy = require('passport-local').Strategy;
 var mongo = require('mongodb');
 var mongoose = require('mongoose');


 //Mongoose Part
 mongoose.connect('mongodb://localhost/loginapp');
 //mongodb
 var db = mongoose.connection;

var routes = require('./routes/index');
var users = require('./routes/users');
var admin = require('./routes/admin');

//start app
// using express for first time to initialize
var app = express();

//Viewing engine start here\
// views folder to handle views
app.set('views', path.join(__dirname, 'views'));
// set hanglebards ass the engine, default layout called layout.handlebars
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
//set to handlebards
app.set('view engine', 'handlebars');
//images
// app.set('view engine', 'ejs')

app.use(express.static('views/images'));

//Middleware config
//Video Tutorial
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(cookieParser());

// Public Folder to hold images, jquery, stylesheets
app.use(express.static(path.join(__dirname, 'public')));

//use of Express session
app.use(session({
  secret: 'secret',
  saveUnitialized: true,
  resave: true
}));

//PASSPORT INNIT FOR VALIDATIOn
app.use(passport.initialize());
app.use(passport.session());

//Express Validator from https://devhub.io/repos/ctavan-express-validator
app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
      var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg   : msg,
      value : value
    };
  }
}));

//connect the flash
app.use(flash());

//set GLOBAL variables for flash messages
app.use(function (req, res, next) {
  //response local sucess message = require flash 'sucess msg'
  res.locals.sucess_msg = req.flash('sucess_msg');
  res.locals.error_msg = req.flash('error_msg');
  //passport error messages
  res.locals.error = req.flash('error');
  //for the nav bar when logged inspect
  res.locals.user = req.user || null;
  next();
});


app.use('/', routes);
// ADMIN BELOW
app.use('/admin', admin);
//UPLAOD BIT
app.use('/users', users);

//Setting the port for the page/app
app.set('port', (process.env.PORT || 3000));

app.listen(app.get('port'), function(){
  console.log('Server Started on Port '+app.get('port'));
})

3 个答案:

答案 0 :(得分:0)

不确定服务器的配置,但是您可以在下面尝试

const port = 3000;

var express = require('express'),
    app = express();
var bodyParser = require('body-parser');

app.use(express.static(__dirname + '/public'));

app.use(bodyParser.urlencoded({
   extended: false;
}));

app.use(bodyParser.json());

router.get('/', function (req, res) {
  console.log("Rendered Upload page")
  res.render('admin');
});

router.post('/upload', upload.single('file'), function (req, res) {
  console.log("Post made")
  res.response({file: req.file});
});

app.listen(port);

答案 1 :(得分:0)

下载,要求并将multer设置到目的地。就在您的//将帖子上传到上传的路径之前,将文件上传到数据库

const multer = require('multer')
const upload = multer({dest: 'images'})

答案 2 :(得分:-1)

请尝试

       <form action ="upload" method ="post" enctype="multipart/form-data">

,并使用邮差测试您的nodejs处理程序是否按预期工作 请查看此链接以使用邮递员上传文件postman file upload

测试发布后,您可以确定哪个部分是错误的部分

还请确保将multer初始化为

var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

在您的处理程序之前