无法在express.js 4.x中的特定路由中获取表单数据

时间:2019-04-26 16:46:54

标签: node.js express body-parser

我无法在特定路线中获取表单数据,但是我可以在主app.js文件中进行console.log记录,但是在路线中却出现未定义的字段错误。

我已经尝试过Express解析打包和body-parser打包,但是仍然给我错误: 这是我的App.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');

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

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

这是我的路线:-

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser')

var jsonParse = bodyParser.json();
var formParse = bodyParser.urlencoded({ extended: false });

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

router.post('/deal', formParse, function(res, req, next){
  res.json(req.body.email)
})
module.exports = router;

这是我的html表单:-

<!DOCTYPE html>
<html>
    <body>
        <form action="/deal" method="POST">
            <input type="text" name="email" id="sad">
            <button type="submit">Send</button>
        </form>
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

尝试一下:

app.js

替换此:

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

与此:

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

indexrouter.js 中 替换为:

router.post('/deal', formParse, function(res, req, next){
  res.json(req.body.email)
})

与此:

router.post('/deal', function(res, req, next){
  res.json(req.body.email)
})