通过前端发送表单时,req.body始终为空

时间:2018-05-31 22:19:15

标签: node.js express body-parser

我只是学习节点和JS,因此我使用mongodb构建了一个非常简单的快速应用程序。该应用程序应该使用表单呈现一个把手模板,以便将用户添加到数据库中。

我的问题是:当我通过浏览器发送表单时,req.body总是空的。当我通过邮递员发送它时它工作,用户被添加到我的数据库。为什么这个以及body-parser缺少什么来解析我的html-form。

这是我到目前为止所做的:

app.js

const express = require('express'),
    app = express(),
    createError = require('http-errors'),
    path = require('path'),
    logger = require('morgan'),
    bodyParser = require('body-parser'),
    exphbs  = require('express-handlebars');

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

app.use(logger('dev')); // Log requests to API using morgan

app.set('views', './views');

app.engine('hbs', exphbs({
    defaultLayout: 'main',
    extname: 'hbs'
}));
app.set('view engine', 'hbs');

app.use(express.static(path.join(__dirname, 'public')));

app.use('/', require('./routes/routes'));

// 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 = process.env.NODE_ENV === 'development' ? err : {};

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

module.exports = app;

视图/ adminAdd.hbs

<div class="row">
    <form class="col s12" id="reg-form" action="/admin/add" name="add-form" enctype="application/x-www-form-urlencoded" method="post">
        <div class="row py-md-2">
            <div class="input-field col col-sm-6">
                <input id="firstname" type="text" class="validate" required>
                <label for="firstname">First Name</label>
            </div>
        </div>
        <div class="row py-md-2">
            <div class="input-field col col-sm-6">
                <input id="lastname" type="text" class="validate" required>
                <label for="lastname">Last Name</label>
            </div>
        </div>
        <div class="row py-md-2">
            <div class="input-field col col-sm-6">
                <input id="email" type="email" class="validate" required>
                <label for="email">Email</label>
            </div>
        </div>
        <div class="row py-md-2">
            <div class="input-field col col-sm-6">
                <input id="password" type="password" class="validate" minlength="6" required>
                <label for="password">Password</label>
            </div>
        </div>
        <div class="row py-md-2">
            <div class="input-field col-sm-6">
                <button class="btn btn-large btn-register btn-primary" type="submit" name="adduser">Add User</button>
            </div>
        </div>
    </form>
</div>

控制器/ adminController

var util = require("util"),
    adminUser = require("../models/adminUserModel");

exports.admin = function(req, res) {
    res.render('admin', {
        showNavBar: true,
        showFooter: false,
        title: 'Admin'
    });
};

exports.adminAddGET = function(req, res) {
    res.render('adminAdd', {
        showNavBar: true,
        showFooter: false,
        title: 'Admin Add'
    });
};

exports.adminAddPOST = function(req, res) {
    console.log("req.body=" + util.inspect(req.body));

    if(!req.body.firstname) {
        res.json({ success: false, message: 'Please provide firstname.' });
    } else if (!req.body.lastname) {
        res.json({ success: false, message: 'Please provide lastname.' });
    } else if (!req.body.email) {
        res.json({ success: false, message: 'Please provide email.' });
    } else if (!req.body.password) {
        res.json({ success: false, message: 'Please provide password.' });
    } else {
        console.log("All Fields filled");

        var newAdminUser = new adminUser({
            firstname: req.body.firstname,
            lastname: req.body.lastname,
            email: req.body.email,
            password: req.body.password
        });
        console.log("newAdminUserObject=" + util.inspect(newAdminUser));

        // Attempt to save the user
        newAdminUser.save(function(err) {
            if (err) {
                console.log("error:" + err);
                return res.json({ success: false, message: 'ERROR - Didnt work' });

            }
            console.log("success");
            res.json({ success: true, message: 'User added successfully!' });
        });
    }
};

路由/ routes.js

var express = require('express'),
    router = express.Router(),
    adminController = require('../controllers/adminController'),
    indexController = require('../controllers/indexController');

router.get('/', indexController.index);

router.get('/admin', adminController.admin);
router.get('/admin/add', adminController.adminAddGET);
router.post('/admin/add', adminController.adminAddPOST);

module.exports = router;

通过邮递员发送以下表格时......

Postman x-www-form-urlencoded

我在终端中看到以下输出,并且用户已成功添加到我的mongodb:

req.body={ firstname: 'dan',
  lastname: 'dan',
  email: 'dan@dan.de',
  password: 'dandan' }
All Fields filled
newAdminUserObject={ role: 'Admin',
  _id: 5b106939991dda2404c0dc6a,
  firstname: 'dan',
  lastname: 'dan',
  email: 'dan@dan.de',
  password: 'dandan' }
success

当我通过浏览器发送表单时,我得到以下输出:

req.body={ adduser: '' }

在浏览器中我看到以下内容:

browser output

从我的角度来看,我将x-www-form-urlencoded的表单以两种方式发送到同一地址。

1 个答案:

答案 0 :(得分:0)

您的表单输入元素缺少“名称”属性。获得{ adduser: '' }的原因是因为表单中唯一具有name属性的input元素是button元素。

<input id="firstname" name="firstname" type="text" class="validate" required>
<input id="email" name="email" type="email" class="validate" required>
...etc