Im new to NodeJS and ExpressJS. Kindly review my code in getting input from the user. Please include best practices, conventions in NodeJS, ExpressJS and JavaScript.
/app.json
:
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, item = require('./routes/item')
, http = require('http')
, path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
app.get('/item/new', item.new);
app.get('/item/save', item.save);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
In /routes/item.js
:
exports.save = function(req, res){
console.log('save' + req.param('itemName'));
//proccess input here
res.redirect('/');
};
In /views/item/new.ejs
:
<!DOCTYPE html>
<html>
<head>
<title>My First ExpressJS Web App</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<p>Welcome to new item page</p>
<form method="get" action="/item/save">
<input type="text" name="itemName" /> <br/>
<input type="submit" />
</form>
</body>
</html>
I just tried to log the input provided by the user at page http://localhost:3000/item/new
.
It works as I expected. But since Im new to this, please provide comments or how can I improve my source code.
/views/item/new.ejs:
and/routes/item.js
works. The inputitemName
is loggedconsole.log('save' + req.param('itemName'));
– JR Galia Jun 11 at 9:05