I don´t know why this code inserts NULL.
When the post request is sent I receive (from res.json(req.body) in index.js) an empty "{}"
I´m using NodeJs, Express 4 and MongoDB.
The name attributes in the post are the same than in the jade
template. I have two forms in the same .jade but with differents names, obviously.
This is not all code, I just put the most important and what is related to the question
App.js
var express = require('express');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/registredUsers');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/', routes);
app.use('/users', users);
module.exports = app;
index.js
var express = require('express');
var bodyParser = require('body-parser');
router.post('/adduser', function(req, res) {
var db = req.db;
var userName = req.body.username;
var userEmail = req.body.useremail;
var userPassword = req.body.userpassword;
var collection = db.get('usercollection');
collection.insert({
username : userName,
email : userEmail,
password : userPassword
}, function (err, doc) {
if (err) {
res.send("There was a problem adding the information to the database.");
}
else {
res.json(req.body);
}
});
});
module.exports = router;
Have you tried putting
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/registredUsers');
At the top of your index.js and removing var db = req.db from the route.
Also, you can return the newly created document from the call back in your response.
Your index.js file would now look like this.
index.js
var express = require('express');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/registredUsers');
router.post('/adduser', function(req, res) {
var userName = req.body.username;
var userEmail = req.body.useremail;
var userPassword = req.body.userpassword;
var collection = db.get('usercollection');
collection.insert({
username : userName,
email : userEmail,
password : userPassword
}, function (err, doc) {
if (err) {
res.send("There was a problem adding the information to the database.");
}
else {
res.json(req.body); // <- here you could return the new object instead.
// res.json(doc);
}
});
});
module.exports = router;
edit
To assist the OP I made the following suggestion:
Hardcode var userName = 'test' and return the created document in res.json(doc) in order to test that the database is updating.
Related
Like i said in title. req.body don't work. I saw some examples and that use req.body(body-parser) well. But in my code, req.body is keep undefined. Also i found same problems and they said "app.use(bodyParser.json())" will work. But for me, no. So i ask how can i solve this error. Plz, help me.
This code is simple, Express and Vue login, signin test project. I think problem is in server file.
Server
var express = require("express");
var bodyParser = require("body-parser");
var path = require("path");
const mongoose = require("mongoose");
var index = require("./routes/index.js");
var login = require("./routes/login.js");
var signin = require("./routes/signin.js");
var app = express();
var http = require("http").Server(app);
mongoose.connect("mongodb://localhost:27017/test");
app.use('/', index);
app.use('/api/login', login);
app.use('/api/signin', signin);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.set("port", process.env.PORT || 3000);
app.use(express.static(path.join(__dirname, 'public')));
http.listen(app.get("port"), function() {
console.log("server start in " + app.get("port"));
})
Router
const express = require("express");
const router = express.Router();
const User = require("../models/user.js");
router.post("/", function(req, res, next) {
const id = req.body.id;
const password = req.body.password;
let info = {
error: "false",
words: "",
id: "",
password: ""
}
User.findOne({ id: id }, function(err, user) {
if(err) {
info.error = "true";
info.words = "Unknown Error Come Out.";
return res.send(info);
}
if(!user) {
info.error = "true";
info.words = "Please Check Your ID or Password";
return res.send(info);
}
info.id = id;
info.password = password;
console.log(info);
return res.send(info);
})
});
module.exports = router;
This body can not be resolved because of your middleware declaration order. You can check from the following blog about middleware execution sequence. Basically it equals to middleware declaration order.
https://derickbailey.com/2016/05/09/in-what-order-does-my-express-js-middleware-execute/
Declare bodyParser middleware before router middleware can solve your problem
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/api/login', login);
I am implementing a simple login functionality and storing the data in the express-session but not able to get it back.
In loginDb.js file in login function i am storing the userId in session variable and in getLoginStatus function i am trying to access the userId but it is returing as undefined.
I have gone through many post related to similar issue but nothing helped in my case. Don't know what i am doing wrong here. Below is the code.
server.js
var express = require('express');
var pg = require('pg');
var cookieParser = require('cookie-parser');
var bodyparser = require('body-parser');
var session = require('express-session');
var path = require('path');
const port = 3000;
const loginroute = require('./Routes/login');
var app=express();
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: 'This is a secret',
resave: true,
saveUninitialized:true,
cookie: {
secure: false,
maxAge: 60000
}
}));
//Routes
app.use('/api/loginroute',loginroute);
app.listen(port,function(){
console.log('app listening to port:'+port);
});
login.js
const express = require('express');
const router = express.Router();
const db = require('../DataAccessLayer/loginDb');
router.get('/getLoginStatus', db.getLoginStatus);
router.post('/login', db.login);
module.exports = router;
loginDb.js
var config = require('../Config/config');
var session = require('express-session');
var pg = require('pg');
var pool = new pg.Pool(config.development.db);
function getLoginStatus(req, res, next){
var userId = req.session.userId;
};
function login(req, res, next) {
pool.connect(function(err, client, done) {
if (err) {
console.log("not able to get connection "+ err);
res.status(400).send(err);
}
var q = "select id from nodetest.users where name=$1 and password=$2";
client.query(q, [req.body.username, req.body.password], function(err, result) {
done();
if(err) {
return console.error('error running query', err);
}
if(result.rowCount>0){
req.session.userId = result.rows[0].id;
}
res.send(result.rows);
});
});
};
module.exports = {
login:login,
getLoginStatus:getLoginStatus
};
Set cookieParser secret key similar as that of express-session secret key will fix the issue.
app.use(cookieParser('This is a secret'))
Doc Says
Using cookie-parser may result in issues if the secret is not the same
between this module and cookie-parser.
I just want to capture the response error from a middleware function, it works if I write the code as follows:
var express = require('express');
var expressValidator = require('express-validator');
var app = express();
var bodyParser = require('body-parser');
var router = require('./routes');
//monk.mongoList();
app.use(bodyParser.urlencoded({extented:true}));
app.use(bodyParser.json());
app.use(expressValidator([]));
var port = process.env.PORT || 8978;
router.get('/',function(req,res,next) {
var error = Error('Article is not found');
next(error.message);
return res.send("Hello World!");
});
app.use(function(err,req,res,next) {
console.log(err + "TET");
})
app.listen(port);
but I want to separate the following code:
app.use(function(err,req,res,next) {
console.log(err + "TET");
})
and use it as follows:
app.js
var express = require('express');
var expressValidator = require('express-validator');
var app = express();
var bodyParser = require('body-parser');
var router = require('./routes');
//monk.mongoList();
app.use(bodyParser.urlencoded({extented:true}));
app.use(bodyParser.json());
app.use(expressValidator([]));
var port = process.env.PORT || 8978;
var test = require('./util/test')
app.use(test.logger);
app.use('/',router);
app.listen(port);
console.log('test node API ' + port );
util/test.js
module.exports.logger = function (err, req, res, next) {
console.log('LOGGED')
next()
}
/routes/index.js EDIT: I just edited the /routes/index.js file to make it more simple
var express = require('express');
var router = express.Router();
var url = require('url');
router.get('/api', function(req, res, next) {
var err = "this is error";
var error = Error (err)
var data = { data: "Succuss"}
if (err) {
next(error.message)
res.json({message:err})
}else {
res.json(data);
}
});
module.exports = router;
When add the above code, nothing appear in the console.
Issue is that db is not working properly
app.js
var express = require('express');
var path = require('path');
var http = require('http');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');
var routes = require('./routes');
var users = require('./routes/users');
var app = express.createServer();
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.use(function(req,res,next){
req.db = db;
next();
});
routes/index.js
exports.index = function(req, res){
var db = req.db;
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
};
When I run userlist I get an error on line db.get('usercollection'). When I log req.db it is undefined.
How to resolve it?
you can directly use your db module in the index.js file
module.exports = (function() {
'use strict';
var apiRoutes = express.Router();
var Server = mongo.Server;
var Db = mongo.Db;
var BSON = mongo.BSONPure;
function connexionDataBase(callback){
var server = new Server('your db URL', 27017, {auto_reconnect: true});
db = new Db('you Db', server);
db.open(function(err, db) {
if(!err) {
console.log("Connected to 'you Db' database");
callback(err,db);
}
else{
console.log("not Connected to 'you Db' database");
callback(err,db);
}
});
})();
and in your app.js your can redirect the app routes to index.js :
var express = require('express');
var index = require('./index');
var app = express();
app.use('/index',index);
I am writing a web service in NodeJS using Express. My problem occurs when I want to use the app (Express instance) in other modules. The following configuration works just fine, but if I replace
var app = module.exports = express();
with
var app = express();
and then use
module.exports = app;
at the bottom of app.js, everything will break down. There will be an error when calling app.get() in the auth module (TypeError: app.get is not a function). Can somebody explain to me why it matters where I export the app object?
app.js
var mongoose = require('mongoose');
var express = require('express');
var bodyParser = require('body-parser');
var debug = require('debug')('app');
var morgan = require('morgan');
var config = require('./config');
var app = module.exports = express();
// --- globals ---
app.set('jwtTokenSecret', config.jwtTokenSecret);
// --- middleware ---
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(morgan('dev'));
// --- routes ---
var courses = require('./routes/courses');
var users = require('./routes/users');
var auth = require('./routes/auth');
app.use('/auth', auth);
app.use('/courses', courses);
app.use('/users', users);
// --- database connection ---
mongoose.set('debug', true);
mongoose.connect(config.database, function(err) {
if (err) {
debug('Could not establish connection to mongodb');
} else {
debug('Successfully connected to mongodb');
}
});
routes/auth.js
var express = require('express');
var router = express.Router();
var moment = require('moment');
var jwt = require('jwt-simple');
var User = require("../models/User");
var debug = require('debug')('app');
var app = require("../app");
// POST /auth
router.post('/', function(req, res, next) {
User.findOne({
'username' : req.body.username
}, function(err, user) {
if (err || !user) {
res.status(401).json({ error: "No user found"});
return;
}
if (user.password != req.body.password) {
res.send(401);
}
debug(app.get('database'));
var expires = moment().add(7, 'days').valueOf();
var token = jwt.encode({
user: user.username,
exp: expires
}, app.get('jwtTokenSecret'));
res.json({
success: true,
token: token
});
});
});
module.exports = router;
It's because you have a circular dependency between app.js and auth.js.
In your app.js file, you are requiring auth.js, and inside auth.js, you are requiring app.js. By moving module.exports = app to the bottom of app.js, it is being called AFTER var auth = require('./routes/auth');. This means that when var app = require("../app"); is called inside auth.js, module.exports will not be yet defined inside app.js, hence leading to the error.