javascript - Nodejs with Express... post data not received in users.js from jade form -
windows 8.1
nodejs express
console output is...
$ npm start > nodeauth@1.0.0 start e:\nodejs\_projects\nodeauth > node ./bin/www /users/register 200 525.115 ms - 2078 /stylesheets/style.css 304 7.118 ms - - /stylesheets/bootstrap.css 304 7.198 ms - - /javascripts/bootstrap.js 304 8.063 ms - - name is... undefined reqname... undefined pw is... undefined pw2 is.. undefined post /users/register 200 79.328 ms - 2340 /stylesheets/bootstrap.css 304 7.847 ms - - /stylesheets/style.css 304 7.378 ms - - /javascripts/bootstrap.js 304 8.676 ms - -
register.jade is...
form loads ok , appears correct
extends layout block content h1 register p complete form site registration ul.errors if errors each error, in errors li.alert.alert-danger #{error.msg} form(method='post',action='/users/register',enctype='multipart/form-data') .form-group input.form-control(name='name', type='text', placeholder='full name') .form-group input.form-control(name='email', type='email', placeholder='valid email') .form-group input.form-control(name='username', type='text', placeholder='username') .form-group input.form-control(name='password', type='password', placeholder='password') .form-group input.form-control(name='password2', type='password', placeholder='confirm password') .form-group label profile image input.form-control(name='profileimage', type='file') input.btn.btn-default(name='submit', type='submit', value='register')
user.js is...
values in console.log statements undefined in console output. post method must not sending form. values users.js errors array displayed after submission. possible syntax error, i'm not seeing it.
var express = require('express'); var router = express.router(); /* users listing. */ router.get('/', function(req, res, next) { res.send('respond resource'); }); 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) { // 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('name is... ', name); console.log('reqname... ', req.body.name); console.log('pw is... ', password); console.log('pw2 is.. ', password2); // check image field if (req.body.profileimage) { console.log('uploading file...'); // file info var profileimageoriginalname = req.files.profileimage.originalname; var profileimagename = req.files.profileimage.name; var profileimagemime = req.files.profileimage.mimetype; var profileimagepath = req.files.profileimage.path; var profileimageext = req.files.profileimage.extension; var profileimagesize = req.files.profileimage.size; } else { var profileimagename = 'noimage.png'; // default image } // form validation using express validator req.checkbody('name', 'name required').notempty(); req.checkbody('email', 'valid email required').notempty(); req.checkbody('email', 'email not valid').isemail(); req.checkbody('username', 'username required').notempty(); req.checkbody('password', 'password required').notempty(); req.checkbody('password2', 'passwords not match').equals(req.body.password); // check errors var errors = req.validationerrors(); if (errors) { res.render('register', { // pass values in user not have retype errors: errors, name: name, email: email, username: username, password: password, password2: password2 }); } else { // create user object var newuser = new user({ name: name, email: email, username: username, password: password, profileimage: profileimagename }); // create user user.createuser(newuser, function(err, user){ if (err) throw err; console.log(user); }); // success req.flash('success', 'you registered , may login'); res.location('/'); res.redirect('/'); } }); module.exports = router;
files not seem valid in following context...
if (req.files.profileimage) console.log('uploading file...');
changed to...
if (req.body.profileimage) console.log('uploading file...');
have not been able test yet.
middleware...
package.json is...
{ "name": "nodeauth", "version": "1.0.0", "private": true, "scripts": { "start": "node ./bin/www" }, "dependencies": { "body-parser": "~1.13.2", "connect-flash": "*", "cookie-parser": "~1.3.5", "debug": "~2.2.0", "express": "~4.13.1", "express-messages": "*", "express-session": "*", "express-validator": "*", "jade": "~1.11.0", "mongodb": "*", "mongoose": "*", "morgan": "~1.6.1", "multer": "^1.0.3", "passport": "*", "passport-http": "*", "passport-local": "*", "serve-favicon": "~2.3.0" } }
, app.js file is...
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 localstrategy = 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 app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // handle file uploads var upload = multer({ dest: './uploads' }); // ??? app.use(multer({dest: './uploads'})); // uncomment after placing 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 ... note: passport middleware must after express session middleware above app.use(passport.initialize()); app.use(passport.session()); // validator // in example, formparam value going morphed form body format useful printing. app.use(expressvalidator({ errorformatter: function(param, msg, value) { var namespace = param.split('.') , root = namespace.shift() , formparam = root; while(namespace.length) { formparam += '[' + namespace.shift() + ']'; } return { param : formparam, msg : msg, value : value }; } })); app.use(cookieparser()); app.use(express.static(path.join(__dirname, 'public'))); // flash , express-messages app.use(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 , forward error handler app.use(function(req, res, next) { var err = new error('not found'); err.status = 404; next(err); }); // error handlers // development error handler // print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
npm install multer did not like...
app.use(multer({dest: './uploads'}));
changed to...
var upload = multer({ dest: './uploads' });
not sure proplems cause yet
i face same problem before. way around problem, add connect-multiparty module project using npm command :
npm install connect-multiparty --save
then add code bellow on top of route file (user.js) after express variable definition.
var express = require('express'); .. var multipart = require('connect-multiparty'); var multipartmiddleware = multipart();
and use multipartmiddleware in router accept files upload.
... router.post('/register', multipartmiddleware, function(req, res, next){ ... ... }
be aware module not recommend use in routes, use ones in want accept uploads. check documentation more detail https://www.npmjs.com/package/connect-multiparty
Comments
Post a Comment