How to redirect in exppress with data? - javascript

I'm using Express 3.4.7 and mongo. I register a new character into my mongo database and then I would like to have my page (route : /game) but I want to get the data of the mongodb (like the _id) of my character.
Here is my code :
exports.newGame = function(ip, db){
return function(req, res){
//req.body return all the field
if(req.body.name && req.body.class) {
db.connect(dbconnection, function(err, db){
if(err) throw err;
var collection = db.collection('test'),
insertObj = {
name : req.body.name,
class : req.body.class
};
collection.insert(insertObj, function(err, data){
if(err) throw err;
console.log(data);
res.render('player/index', data); //Here is my problem
});
});
} else {
res.render('home/new', {title : 'Donjon & Gradon - New', ip : ip});
}
}
};
I would like to have the /game page and passing data and db after the query to mongo is OK.
I don't know if I am clear.
Can you help me ?
Regards,
Arnaud

Related

post method in express on other other router

how can i make a post request from a router, it works on the "/" pages but not working on the "/forget" page. when i replace "/forget" page to "/" pages it works fine but when the post method is from "/forget" it give error. here is my code
please help look at it
thanks in advance
this is my "/" pages it works fine here
var express = require('express');
var router = express.Router();
router.post('/activate', function(req, res) {
var register = {
Email: req.body.emial,
Password: req.body.password,
C_password: req.body.c_password
}
var newUser = {
Referer_mail : req.body.ref_email,
Name : req.body.name,
Country : req.body.country,
Phone: req.body.phone,
Email: req.body.emial,
Wallet : 0 ,
Invest : 0 ,
Interest : 0 ,
Income : 0,
referal : 0
}
if (register.Password === register.C_password){
firebase.registerWithEmail(register.Email, register.Password, newUser, function(err, result){
if (err){
console.log(err);
Message = err.message;
}else {
// send emial verification
firebase.sendVerificationEmail(result.token, function(err, result){
if (err){
console.log(err);
Message = err.message;
}else {
console.log(result);
}
});
// save name in data base
firebase.database().ref("Profile").child(result.user.id).set({newUser}, function (err, result){
if (err){
console.log(err);
Message = err.message;
} else {
console.log(result);
}
})
console.log(result);
}
});
res.render('pages/activate', {
value : Message
});
} else {
console.log("password and confrim password not equal");
res.render('pages/index', {
value : " Your Password and Confrim Password are not equal"
});
}
});
while this is my "/forget" pages give error
var express = require('express');
var router = express.Router();
router.post('/activate', function(req, res) {
res.render('pages/activate', {
value : Message
});
});
please help me find time and look at it,
thanks in advance

In express.js, res.render() is not working

I'm making a simple webapp with facebook login.
If the facebook login button on my page is clicked,
FB.api(
'/me',
'GET',
{"fields":"id,name,birthday,gender"},
function(response) {
$.post('fb_login', response, "json");
}
);
is called, and a router handles '/fb_login' request; in the router the server checks the id of json object is already in its DB. If not, res.render('signup', ...) should be called.
However it didn't work. I already checked that res.render() was called, but the page 'signup.jade' didn't show up.
Here is my source code of router.
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '1012'
});
/* GET home page. */
router.post('/', function(req, res, next) {
var userid = req.body.id;
if (userid) {
pool.getConnection(function(err, connection) {
if (err) {
console.error('DB Connection error!!');
return;
}
console.log('DB Connection Success!!');
connection.query('use vasket');
connection.query('select count(*) result from user where userID=?',
[userid], function(err, result, field) {
var isAlreadyUser = result[0].result;
console.log(isAlreadyUser);
if (isAlreadyUser == 1) {
req.session.userid = userid;
res.redirect('/');
res.end();
console.log('DB FB Login Success!!');
connection.release();
}
else {
connection.release();
console.log('FIRST TIME!');
//This method was called, but the page rendered didn't
res.render('signup', {id: req.body.id, name: req.body.name, birthday: req.body.birthday, gender: req.body.gender});
}
});
});
} else {
res.redirect('/');
res.end();
}
How can I fix it?
To help debugging maybe you can modify your code like that :
// ... your code before
else {
connection.release();
console.log('FIRST TIME!');
console.log(req.body);
//This method was called, but the page rendered didn't
res.render(
'signup',
{
id : req.body.id,
name : req.body.name,
birthday: req.body.birthday,
gender : req.body.gender
} ,
function(err, html){
if(err) console.log(err);
console.log(html);
//res.send(html);
// trying same but forcing status
res.status(200).send(html);
}
);
}
});
});
} else {
res.redirect('/');
res.end();
}
This is an older question, but it's still in need of a solid answer. I had the exact same problem, but I think I've figured it out.
If the server's returning the proper response, that's not where your problem lies. jQuery (in the browser) will render the response, but you have to tell it to do so.
Here's what I had that was responding properly but not rendering:
$("#getsome").click(function() {
$.get("/task/create");
});
And here's how I got it to render:
$("#getsome").click(function() {
$.get("/task/create", function( data ) {
document.write(data);
});
});
Note that you may not need to replace the entire DOM like I'm doing.
References:
Replacing the entire
DOM
jQuery.get

Node.js Object [object Object] has no method error

I am using Express.js for my app and mongodb for database (also mongodb Nativ driver).
I created a model with two functions, for getting posts and comments:
// Get single Post
exports.posts = function(id,callback){
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
console.log('Connection established to', url);
var collection = db.collection('posts');
collection.find({psotId:id}).limit(1).toArray(function (err, result) {
if (err) {
return callback(new Error("An error has occured"));
} else {
callback(null,result);
}
db.close();
});
}
});
}
// Get post comments
exports.comments = function(id,callback){
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
console.log('Connection established to', url);
var collection = db.collection('comments');
collection.find({postId:id}).toArray(function (err, result) {
if (err) {
return callback(new Error("An error has occured"));
}
else {
callback(null,result);
}
db.close();
});
}
});
}
and I created a route to show single post:
var post = require('../models/post');
//Get single post
router.get('/post/:postId',function(req,res, next){
var id = parseInt(req.params.postId);
post.posts(id,function(err,post){
if(err){
console.log(err)
}else{
post.comments(post[0].id,function(err,comments){
if(err){
console.log(err)
}
else{
res.render('blogPost',{post:post,comments:comments})
}
})
}
})
})
When I run this code I get this error:
TypeError: Object [object Object] has no method 'comments'
When I use this two function separately its work fine:
I mean like this :
var post = require('../models/post');
//Get single post
router.get('/post/:postId',function(req,res, next){
var id = parseInt(req.params.postId);
post.posts(id,function(err,post){
if(err){
console.log(err)
}else{
res.render('blogPost',{post:post})
}
})
})
//Get post comments
router.get('/post/1',function(req,res, next){
post.comments(1,function(err,comments){
if(err){
console.log(err)
}else{
res.render('blogPost',{comments:comments})
}
})
})
But when I use post.comments as callback for post.posts I get an error.
I wants know why this happening? After some research I couldn't find a solution and I an getting confused.
In your source code you have the following:
var post = require('../models/post');
//Get single post
router.get('/post/:postId',function(req,res, next){
var id = parseInt(req.params.postId);
post.posts(id,function(err,post){
if(err){
console.log(err)
}else{
post.comments(post[0].id,function(err,comments){
if(err){
console.log(err)
}
else{
res.render('blogPost',{post:post,comments:comments})
}
})
}
})
})
when you are calling post.posts you have a callback and there you have a return value which you called post (which it is the same variable name of var post = require('../models/post');
Basically change it in the callback like this:
var post = require('../models/post');
//Get single post
router.get('/post/:postId',function(req,res, next){
var id = parseInt(req.params.postId);
post.posts(id,function(err,posts){ //HERE changed post into posts
if(err){
console.log(err)
}else{
post.comments(posts[0].id,function(err,comments){
if(err){
console.log(err)
}
else{
res.render('blogPost',{post:posts,comments:comments})
}
})
}
})
})
EDIT: for better understanding I would change var post = require('../models/post'); into var postModel = require('../models/post'); SO it is much more understandable
EDIT 2: since he posted the real version code
Basically you have the same problem, line 37 of route.js is overriding the movie variable.
You have to call the variable that comes back form the callback with another name, for example movieslike you used to do in the other 2 above.
router.get('/m/:movieId',function(req,res, next){
var id = parseInt(req.params.movieId);
movie.get(id,function(err,movies){
if(err){
console.log(err)
}else{
movie.subtitles(movies[0].imdb,function(err,subs){
if(err){
console.log(err)
}
else{
res.render('moviePage',{movie:movies,subtitles:subs})
}
})
}
})
})
If you copy-pasted this from your source then its because you mispelled the method.
post.commencts
should be
post.comments

Upload an image from a client-side webpage

One of the modules in our project is to upload an image from a webpage to mongo database using nodejs. We have completed connecting to a mongo database and upload an image using physical location of the image on the system, but we are not able to make the upload dynamic from a webpage.
We convert the image to a base64 code and then save it to the database. MongoDB returns a unique id. We want to integrate this process and make it dynamic. The code we used to connect to mongoDB and upload an image from physical location is available here.
var MongoClient = require('mongodb').MongoClient,
format = require('util').format,
fs = require('fs'),
http = require('http');
http.createServer(function (req, res) {
//should be triggered by the user upload button
put();
//triggered after the upload/button click
res.writeHead(200, {'Content-Type': 'text/html'});
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) throw err;
var collection = db.collection('test_insert');
collection.find().toArray(function(err, results) {
//console.dir(results);
// Let's close the db
//ret = results[0];
console.log(results[0]);
res.end('<img alt="sample" src="data:image/png;base64,' + results[0].image + '">');
db.close();
});
});
//res.end("Hello World\n");
}).listen(3030);
function read() {
var image_base64 = fs.readFileSync('./uploads/2088-1nqsb3l.jpg').toString('base64');
return image_base64;
//console.log(base64_data);
}
function put() {
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) throw err;
var collection = db.collection('test_insert');
collection.insert({image: read()}, function(err, docs) {
console.log("data inserted");
db.close();
});
});
}
function get() {
var ret;
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) throw err;
var collection = db.collection('test_insert');
collection.find().toArray(function(err, results) {
//console.dir(results);
// Let's close the db
ret = results[0];
db.close();
});
});
return ret;
}
/*
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) throw err;
var collection = db.collection('test_insert');
collection.insert({a: base64_data}, function(err, docs) {
collection.count(function(err, count) {
console.log(format("count = %s", count));
});
// Locate all the entries using find
collection.find().toArray(function(err, results) {
console.dir(results);
// Let's close the db
db.close();
});
});
});
*/
You have to send the image via XMLHttpRequest from the client to nodejs. Then store it in mongo like you did with the file, you read by fs.readFileSync.

MongoDb insert via Node.js Native Driver not inserting

I'm trying to get some data to save into MongoDb. I followed the following example beforehand and verified that it works, however now that I'm trying to write my own test app using this "format" it's not working. MongoDb does not throw any errors and I can even retrieve the doc _id from the insert callback. However when I go into the Mongo shell, the collection doesn't even exist let alone the document.
Here's the example I followed originally just so you can get a feel for the way I tried to mimic for my own test app:
http://blog.ijasoneverett.com/2013/03/a-sample-app-with-node-js-express-and-mongodb-part-1/
Below is my attempt that is failing. Thanks for any help!
Here's my DB code:
var Db = require('mongodb').Db,
Connection = require('mongodb').Connection,
Server = require('mongodb').Server,
BSON = require('mongodb').BSON,
ObjectID = require('mongodb').ObjectID;
Repository = function(host, port){
this.db = new Db('test-mongo-db', new Server(host, port, {safe: true}, {auto_reconnect:true}, {}));
this.db.open(function(){
console.log('db open');
});
};
Repository.prototype.getCollection = function(callback){
this.db.collection('owners', function(error, owners_collection){
if (error) callback(error);
else
callback(null, owners_collection);
});
};
Repository.prototype.createOwner = function(owner, callback){
this.getCollection(function(error, owners_collection){
if (error) callback(error);
else {
owners_collection.insert(owner, function(error, doc){
if (error) callback(error);
else {
console.log('insert was successful: ' + doc[0]['_id']);
callback(null, owner);
}
});
}
});
};
exports.Repository = Repository;
Here's the code that's calling it:
var Repository = require('../repositories/Repository').Repository;
exports.createOwner = function(req, res){
var owner = {
email : req.body.email,
password : req.body.password,
firstName : req.body.firstName,
lastName : req.body.lastName,
schools : []
};
var repository = new Repository('localhost', 27017);
repository.createOwner(owner, function(error, docs){
if (error) console.log('saving owner failed : ' + error);
else {
console.log('saving owner successful');
res.redirect('/');
}
});
};
If #cristkv is right, you can try to add optional parameter write concern in the insert operation:
owners_collection.insert(owner, {w:1}, function(error, doc){
sources:
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insert
http://docs.mongodb.org/manual/core/write-concern/

Categories