关于javascript:Express req.body not working

Express req.body not Working

我是第一次在这里发帖所以如果有什么不对的帖子那么请告诉我。
我是节点和表达新手。 我创建了一个简单的注册表单,但是当我按下Register(提交)按钮时,我将req.body.name作为"undefiend"。
下面我附上了我的app.js,users.js和register.jade文件。

register.jade

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
extends layout

    block content
        h1 Register
        p Please Register using a form below
        ul.errors
            if errors
                each error , i in errors
                    li.alert.alert-danger #{error.msg}
        form(method='post',action='/users/register',enctype='multipart/form-data')
            .form-group
                label Name
                input.form-control(name='name',type='text',placeholder='Enter Your Lucky Name')
            .form-group
                label Email
                input.form-control(name='email',type='email',placeholder='Enter Your Email')
            .form-group
                label Password
                input.form-control(name='password',type='password',placeholder='Enter Password')
            .form-group
                label Confirm Password
                input.form-control(name='password2',type='password',placeholder='Enter Password')
            .form-group
                label Profie Image
                input.form-control(name='profileimage',type='file')

            input.btn.btn-default(name='submit',type='submit',value='Register')

app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator=require('express-validator');
var cookieParser = require('cookie-parser');
var session=require('express-session');
var passport=require('passport');
var LocalStartegy=require('passport-local').Strategy;
var bodyParser = require('body-parser');
//var multer=require('multer');
var flash=require('connect-flash');
var mongo=require('mongodb');
var mongoose=require('mongoose');
var db=mongoose.connection;
//var upload=multer({dest:'./uploads'});
var routes = require('./routes/index');
var users = require('./routes/users');
var multer = require('multer');
var upload = multer({ dest: './uploads' });
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
//Handle file upload
app.use(multer({dest:'./uploads'}));

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//Handle express sessions
app.use(session({
    secret:'secret',
    saveUninitialized:true,
    resave:true
}));
//passport
app.use(passport.initialize());
app.use(passport.session());
app.use(expressValidator());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use(require('connect-flash')());
app.use(function (req, res, next) {
    res.locals.messages = require('express-messages')(req, res);
        next();
});

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

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// 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;

users.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    var express = require('express');
    var router = express.Router();
    var User = require('../models/user');
    /* GET users listing. */
    router.get('/', function(req, res, next) {
        res.send('respond with a resource');
    });
    /* GET users listing. */
    router.get('/register', function(req, res, next) {
        res.render('register',{
            'title':'Register'
        });
    });

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

    router.post('/register',function(req,res,next){
    //Get form Values
        var name=req.body.name;
        var email=req.body.email;
        //var username=req.body.username;
        var password=req.body.password;
        var password2=req.body.password2;
        console.log('hello ' +req.body);  //gets hello [object Object]
        console.log('hello' + req.body.name); //H=hello undefined


    //Check For Image Field
    if(req.files.profileimage){
        console.log("uploding file");
        var profileImageOriginalName=req.files.profileimage.originalname;
        var profileImageName=req.files.profileimage.name;
        var profileImageMime=req.files.profileimage.mime;
        var profileImagePath=req.files.profileimage.path;
        var profileImageExt=req.files.profileimage.extension;
        var profileImageSize=req.files.profileimage.size;
    }else{
        var profileImageName='NoImage.png';
    }

    //Form Validation

    req.checkBody('name','Name Field is Required').notEmpty();
    req.checkBody('email','Email Field is Required').notEmpty();
    req.checkBody('email','Enter Correct Email').isEmail();
    req.checkBody('password','Password  Field is Reqired').notEmpty();
    req.checkBody('password2','Password Doesn\'t match').equals(req.body.password);

    //Check For Errors

    var errors=req.validationErrors();
    if(errors){
        res.render('register',{
            errors:errors,
            name:name,
            email:email,
            username:username,
            password:password,
            password2:password2
        });
    }else{
            var newUser=new User({
            name:name,
            email:email,
            // username:username,
            password:password,
            //profileimage:profileImageName
        });

        User.createUser(newUser,function(err,user){
        if(err) throw err;
        console.log(user);

        });


        req.flash('success','You Have Successfulyy Registerd');
        res.location('/');
        res.redirect('/');
        }

    });
    module.exports = router;


body属性不是Response的成员,它是Request的成员。 所以你的代码应该是正确的,如下所示。

Use console.log('hello ' + req.body); instead of console.log('hello
' + res.body);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
var express = require('express');
var router = express.Router();
var User = require('../models/user');

/* GET users listing. */
router.get('/', function (req, res, next) {
    res.send('respond with a resource');
});
/* GET users listing. */
router.get('/register', function (req, res, next) {
    res.render('register', {
        'title': 'Register'
    });
});

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

router.post('/register', function (req, res, next) {
    //Get form Values
    var name = req.body.name;
    var email = req.body.email;
    //var username=req.body.username;
    var password = req.body.password;
    var password2 = req.body.password2;

    console.log('hello ' + req.body);  //gets undefined


    //Check For Image Field
    if (req.files.profileimage) {
        console.log("uploding file");
        var profileImageOriginalName = req.files.profileimage.originalname;
        var profileImageName = req.files.profileimage.name;
        var profileImageMime = req.files.profileimage.mime;
        var profileImagePath = req.files.profileimage.path;
        var profileImageExt = req.files.profileimage.extension;
        var profileImageSize = req.files.profileimage.size;
    } else {
        var profileImageName = 'NoImage.png';
    }

    //Form Validation

    req.checkBody('name', 'Name Field is Required').notEmpty();
    req.checkBody('email', 'Email Field is Required').notEmpty();
    req.checkBody('email', 'Enter Correct Email').isEmail();
    req.checkBody('password', 'Password  Field is Reqired').notEmpty();
    req.checkBody('password2', 'Password Doesn\'t match').equals(req.body.password);

    //Check For Errors

    var errors = req.validationErrors();
    if (errors) {
        res.render('register', {
            errors: errors,
            name: name,
            email: email,
            username: username,
            password: password,
            password2: password2
        });
    } else {
        var newUser = new User({
            name: name,
            email: email,
            // username:username,
            password: password,
            //profileimage:profileImageName
        });

        User.createUser(newUser, function (err, user) {
            if (err) throw err;
            console.log(user);

        });


        req.flash('success', 'You Have Successfulyy Registerd');
        res.location('/');
        res.redirect('/');
    }

});
module.exports = router;