How to access the post body in express route? - javascript

I am learning how to build a web app using express, node, and angular. I have a post request from angular, and I can successfully send that to the router in login.js:
var user = {username: $scope.userName, password: $scope.password};
$scope.login = function() {
console.log('attempting to log in,,');
console.log("The useranem" + $scope.userName + " " + $scope.password + " " + user);
$http.post('/userLogin', user).then(successCallback, errorCallback);
};
index.js
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'xxxxx',
database : 'xxxxx'
});
connection.connect();
router.post('/userLogin', function(req, res, next){
console.log('the user name is ' + req.body);
});
module.exports = router;
From the image, I can see that I was able to print out the body of the post request as objects. Is this because I don't have body parser in index.js.
I already installed body parser in app.js,
1) do I have to require app.js in index.js to use the body parser?
2)And once I am able to parse the body, how do I access the varaibles in the body. Would it be req.username and req.password?
3) This question is not as related, but in my app.js I have app.use('/', login). How do i determine what the path should be? Should it be the same as the express router such as /userLogin?
This is my app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var routes = require('./routes/index');
var register = require('./routes/register');
var users = require('./routes/users');
var login = require('./routes/login');
var app = express();
//establish database connection
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'xxxxx',
database : 'xxxxx'
});
connection.connect();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/', login);
//add route for registering account
// 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 handlers
// development error handler
// will 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 to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Note: most of the stuff in app.js was created using express generator.

Looks like you need to access the data from req.body that you want. So if the object you want to access from that is user from the json object you'd need to access req.body.user

You are trying to concatenate an object with a string. This forces the standard output to call the method toString() from the object which results in [object Object] if it's not overridden with a custom implementation.
To see the whole object, you can use: console.log(req.body);
then you will be able to see the object.

Related

node.js/express.js connection pool Cannot read properties of undefined (reading 'getConnection')

So I created a new node.js project and used express.js to build the basics to start of. Now I want to do a simple get call to get data from my database through a connection pool. When I do the call in app.js there is no problem, but when trying to do the same call from my users.js file in a get route it throws 'connection pool Cannot read properties of undefined (reading 'getConnection')'.
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mysql = require('mysql');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// establish connection to database
var conpool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: '****',
password: '****',
database: 'db_name'
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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, conpool};
user.js (located in routes directory which is on the same hierarchy level as app.js)
var express = require('express');
var router = express.Router();
var db = require('../app').conpool;
/* GET users listing. */
router.get('/get', function (req, res, next) {
db.getConnection((err, connection) => {
if (err) throw err;
var sql = null;
if (req.query.name) {
sql = 'SELECT * FROM users WHERE name = ' + sql.escape(req.query.name);
} else {
sql = 'SELECT * FROM users';
}
connection.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});
});
module.exports = router;
Does anyone have any idea why this is happening? Is there something wrong with how I am using module.exports? Is it a problem of trying to call a function on a reference instead of the original pool object?
It seems Evert's solution was the one I was looking for. I'll describe the changes I made compared to the files shown in my question to show how it solved it.
I made a completely new file database.js (on the same level of hierarchy as app.js):
var mysql = require('mysql');
var conpool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: '****',
password: '****',
database: 'db_name'
});
module.exports = conpool;
and deleted all these lines of code from app.js
in user.js only one line changed:
var db = require('../app.js')
to
var db = require('../database');

Can't display data from Mongo database

I'm following this tutorial: http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/
When I do db.usercollection.find().pretty() in my mongo terminal, my records print - so I know I have records to display.
When I do http://localhost:3000/userlist in my browser, I get the words "User List" at the top - but I don't get any of the user data.
It should look like this.
Question: Is my link in my userlist.jade file not pointing to the database data??
userlist.jade
extends layout
block content
h1.
User List
ul
each user, i in userlist
li
a(href="mailto:#{user.email}")= user.username
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/* GET Userlist page. */
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
module.exports = router;
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// new code
// we want to talk to mongodb, use monk to do it, databasebase is lcoated at localhost:27017/nodetest1
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');
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');
// 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 }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Make our db accessible to our router - new code
app.use(function(req,res,next){
req.db = db;
next();
});
// telling Express what route files to use
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 handlers
// development error handler
// will 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 to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
// our master app exporting its app object. All modules export an object whch can easily be called elsewhere in code.
module.exports = app;
i was getting the same error and then i fixed the problem:
app.js
var db = monk('localhost:27017/nodetest1');
change the localhost to 127.0.0.1
and make sure the collection name is nodetest1

express post request won't get data

lately i started to play around with express.js the nodejs web framework. i'm making a simple form that send data to a express route.
I have a users.js route file and inside that there is a register route.
my user.js route file
router.post('/register', function(req, res, next) {
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var passwordConfirm = req.body.passwordConfirm;
console.log(name);
my jade file which form is in it
form(method='post',action='/users/register',enctype='multipart/form-data')
.form-group
label Name
input.form-control(name='name',type='text',placeholder='Enter Name')
and go on ...
console.log retunrs undefiend.
my app.js . I used express generator to generate project, as you can see i have multer and bodyparser
var bodyParser = require('body-parser');
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 multer = require('multer');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
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');
// multer config inja
var upload = 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 session
app.use(session({
secret: 'secret', //encryption key
saveUninitialized:true,
resave:true
}));
// // Passport
app.use(passport.initialize());
app.use(passport.session());
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 messaging via connect-flash
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 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will 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 to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
You have to configure an express middleware to parse the body of your HTTP request before hitting your /register route.
multipart/form-data enctype
This kind of type is often use for file upload. A library like Multer can be helpful for this use case.
I don't see a file to upload in your example. So you should consider using a simple enctype like application/x-www-form-urlencoded enctype (default) (see below).
If you still want to use form-data enctype without file upload, you can use a library like express-busboy (built on top of busboy).
var app = express();
var bb = require('express-busboy');
bb.extend(app);
// ...
router.post('/register', function(req, res, next) {
// req.body contains your fields.
// ...
application/x-www-form-urlencoded enctype (default)
If you configure your form to use the application/x-www-form-urlencoded enctype, it's a little bit easier to handle in your route.
body-parser can be use as a middleware too: https://github.com/expressjs/body-parser#bodyparserurlencodedoptions
var app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded());
// ...
router.post('/register', function(req, res, next) {
// ...
```

NodeJS - get property for Mongodb not working while connecting

I am new to NodeJS and ExpressJS. I am following this tutorial http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/ for creating and connecting mongodb with nodejs. Everything works perfectly(DB data inserting through command line,package.json config) except db connection, it throws undefined error.
var monk = require('monk');
var db = monk('localhost:27017/deno');
I check this in console like this console.log(db) it shows 'undefined' in index.js
My app.js is :
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// New Code
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/Fujitsu');
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');
// 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 }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Make our db accessible to our router
app.use(function(req,res,next){
req.db = db;
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 handlers
// development error handler
// will 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 to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
routes/index.js is
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/************ Customized starts Here **********/
/* GET Userlist page. */
router.get('/userlist', function(req, res) {
var db = req.db;
console.log(db);
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
/******** Customized - Ends here ***********/
module.exports = router;
Please anyone of you tell me the solution because now I'm struggling with this.
Thanks In Advance.

Node.js (with Express.js) not working with Share.js

I'm following the docs on the github of Share.js but can't seem to get it to work
https://github.com/share/ShareJS/wiki/Getting-started-%280.6.x%29
I built a base app with the Express generator. It put the main server file inside /bin/www which is not supposed to be modified (I tried it).
The problem is with the code below.
var connect = require('connect'),
sharejs = require('share').server;
var server = connect(
connect.logger(),
connect.static(__dirname + '/public')
);
var options = {db: {type: 'none'}}; // See docs for options. {type: 'redis'} to enable persistance.
// Attach the sharejs REST and Socket.io interfaces to the server
sharejs.attach(server, options);
server.listen(8000, function(){
console.log('Server running at http://127.0.0.1:8000/');
});
It requires me to set up server.listen(...) in the app.js but it's already been done in the /bin/www file.
My app.js looks like the code below.
var express = require('express');
var engine = require('ejs-locals');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('ejs', engine);
app.set('view engine', 'ejs');
// database setup
var dbConfig = require('./db.js');
var mongoose = require('mongoose');
// connect to DB
mongoose.connect(dbConfig.url, function (err) {
if (err) {
console.log(err);
}
});
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
app.use(expressSession({
secret: 'mySecretKey',
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
// Using the flash middleware provided by connect-flash to store messages in session
// and displaying in templates
var flash = require('connect-flash');
app.use(flash());
// Initialize passport
var initPassport = require('./passport/init');
initPassport(passport);
// Configuring Routes
var routes = require('./routes/index')(passport);
var users = require('./routes/users');
var editor = require('./routes/editor')(passport);
app.use('/', routes);
app.use('/editor', editor);
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;
if (req.session.user) {
app.locals.user = req.session.user
}
next(err);
});
// error handlers
// development error handler
// will 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 to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;

Categories

Resources