无法在快递中发布到服务器

时间:2017-11-17 12:45:05

标签: node.js express sequelize.js

我有一个快速应用程序,它接受基本的用户输入数据。我的所有get路由都运行正常,但是当向服务器提交帖子请求时,我在网址上获得了404,即使我在我的视图文件夹中有此页面,我也会发帖。

app.js:

var express = require('express');
var path = require('path');
var consolidate = require('consolidate');
var bodyParser = require('body-parser');
var database = require('./database/database');
var Patient = require('./models/models').Patient;
var morgan = require('morgan');
var routes = require('./routes');
var app = express();

app.engine('html', consolidate.nunjucks);

app.set('view engine', 'html');
app.set('views', './views');

app.use(morgan('dev'));
//app.use(app.router);
app.use(routes);

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

app.listen(3055);

module.exports = app;

routes / index.js:

const express = require('express');
var bodyParser = require('body-parser');
var Patient = require('../models/models').Patient;
const router = express.Router();

router.get('/', function(req, res, next){
    res.render('index.html');
});

router.post('/addsubject', function(req, res, next){
    Patient.create(req.body).then(function(patient){
        res.redirect('/profile');
    }).catch(function(err){
        if(error.name === "SequelizeValidationError"){
       } else {
       return next(err);
       }
   }).catch(function(error){
      res.send(500, error);
   });
});

router.get('/profile', function(req, res, next){
    res.render('./profile.html');
});

router.get('/addsubject', function(req, res, next){
    // .... do something here ..
});

module.exports = router;

我的index.html文件中有<form action="/addsubject" method="post">

index.html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>dabl Demographic</title>
  <body>
    <h2>Add Subject</h2>
      <form action="/addsubject" method="post">
        <label for="fname">First Name: </label>
        <input type="text" name="fname" id="fname">
        <br>
        <label for="sname">Second Name: </label>
        <input type="text" name="sname" id="sname">
        <br>
        <label for="dob">dob: </label>
        <input type="text" name="dob" id="dob">
        <br>
        <label for="laterality">Laterality: </label>
        <input type="text" name="laterality" id="laterality">
        <br>
        <button>Submit</button>
      </form>
  </body>
</html>

3 个答案:

答案 0 :(得分:2)

body-parser

之前使用app.router中间件
...
app.use(bodyParser.urlencoded({ extended: false }));

app.use(morgan('dev'));
//app.use(app.router);
app.use(routes);
...

答案 1 :(得分:2)

您将错误的功能(错误处理功能)传递给POST路由。

首先删除#34;错误&#34;像这样的函数的参数:

"Field Two"

答案 2 :(得分:0)

问题解决了:

}).catch(function(err){
        if(error.name === "SequelizeValidationError"){
          next(err); //next(err); called inide this block no more 404 error
       } 

用户输入现在已成功通过正文解析器。