404无法使用Express&hbs发布信息

时间:2019-01-28 06:22:16

标签: node.js express

Node Express(4.16)+ Multer(3.2.3)能够上传照片。现在想在接收上传后显示一些动态消息,所以我尝试了hbs(不是Express-Handlbars或Express-hbs),模板提示输入文件ok,但是总是得到

enter image description here

应用程序结构

enter image description here

app.js

const express = require('express')
const bodyParser= require('body-parser')
var path = require('path');
const app = express();
const multer = require('multer');
fs = require('fs-extra');
app.use(bodyParser.urlencoded({extended: false}));
var index = require("./route/index");
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use('/', index);
app.post('*', index);

index.js

const express = require('express');
const r = express.Router();
const bodyParser= require('body-parser');
const app = express();
const multer = require('multer');
fs = require('fs-extra');
app.use(bodyParser.urlencoded({extended: false}));

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads')         // uploads = name of the destination folder
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
})

var upload = multer({ storage: storage });

app.post('/', upload.single('picture'), (req, res) => {
    var img = fs.readFileSync(req.file.path);
});

r.get('/', function(req, res){
  res.render('index');
});
app.post('/', upload.single('picture'), (req, res) => {
    var img = fs.readFileSync(req.file.path);
    });

app.post('/uploadphoto', upload.single('picture'), (req, res) => {
  var i = 1;
  ...
});

module.exports = r; 

index.hbs

<form action="/uploadphoto" enctype="multipart/form-data" method="POST"> 
  Single Img.
  <input type="file" name="picture" accept="image/*" />
  <input type="submit" value="Upload an Image"/>
</form>
<h2>{{dynamicHere}}</h2>

已经检查了其他SO,包括Cannot POST / error using expressCannot POST form node.js - express

提琴手仅显示状态404和“无法发布”。在VSC中不会达到任何断点。

1 个答案:

答案 0 :(得分:1)

您正在导出r,其中仅包含一条路由r.get('/', function(req, res){})。要使用/uploadphoto,您需要导出app

module.exports = app;