Pass values from Server to Client | Node to Angular - javascript

I'm very new to MEAN. I'm trying to send a dataset from Node to my Angular Controller. However, the angular controller isn't receiving the correct information and is resulting in null.
My view is called booklist.jade
Here is my server side (Node JS)
router.get('/thelist', function(req, res){
res.render('booklist');
});
router.get('/thelist/data', function(req, res){
.
.
.
// Find all books
collection.find({}).toArray(function (err, result) {
if (err) {
res.send(err);
} else if (result.length) {
res.json({booklist : result});
} else {
res.send('No documents found');
}
//Close connection
db.close();
});
}
});
});
Here is my client side (Angular JS)
function booksController($scope)
{
$http.get("http://localhost:3000/thelist/data").success(function( data ) {
$scope.book=10; //THIS WORKS
$scope.table= data;
});
}
Basically, I want $scope.table to have all data from my server. Any ideas on why this is failing?
UPDATE: On trying some console log checks, I found out that the request router.get('/thelist/data', function(req, res) isn't being called by the Angular Controller.

res.json({booklist : result});
as per your code you are sending result in booklist attribute
Hence while reading you should say $scope.table= data.booklist;

My client side controller was wrong. Here is the correct one.
app.controller('booksController',['$scope','$http',
function($scope,$http) {
$http.get("http://localhost:3000/thelist/data").success(function( data ) {
$scope.book=data;
});
}]);

Related

Add an error page to this express app?

I'm building an express app, a basic twitter interface.
I want to add an error page to the application, so that if anything goes wrong with the routes the user will see a friendly message rendered, instead of the default error code.
Here is a snippet of my code:
//Tell app to render template
app.get('/', function(req, res){
if(!error){
res.render('index', {
myName: myName,
profileImage: profileImage,
screenName: screenName,
followerCount: followerCount,
dateTweeted: dateTweeted,
tweetContent: tweetContent,
noOfRetweets: noOfRetweets,
noOfLikes: noOfLikes,
});
}
});
Why can't I just do this?
else{
res.send('sorry, bro, page not found!);
}
Or do I need to do something with passing the error to the 'next’ handler? I can't get my head around how that works.
Would really appreciate some help please!
Your question is not very specific but I assume you will get some errors during manipulation.
Then you can send type of error like this after getting error
//Tell app to render template
app.get('/', function(req, res) {
if ("not error") {
//You can do whatever you want
res.status(200).send({message:"Success message"})
}else{//If error you can choose your error code with relevant message
res.status(400).send({message:"Bad request error"});
//OR
res.status(404).send({message:"Not found error"});
//OR
res.status(401).send({message:"Unauthorization error"});
//OR
res.send(500).send({message:"Any server side erorr"});
}
});
You can build a custom middlewarethat does this for you...
function errorMiddleware(req, res, next) {
// implement some logic, do your check...
let thereAreErrors = /* ? */ false;
if(!thereAreErrors) {
return next();
}
return res.status(400).end();
}
function indexRouteCtrl(req, res) {
return res.render('index');
}
app.get('/'/, errorMiddleware, indexRouteCtrl);

MongoDB&NodeJS: How to display a certain field on a Jade file on a server

So I just started learning MEAN and I want to show only a certain field of a database I've made to a Node server. I'm using Express as well. Here is my code so far.
index.js
router.get('/generate', function(req, res) {
// get out mongoclient to work with our mongo server
var MongoClient = mongodb.MongoClient;
// where the mongodb server is
var url = 'mongodb://localhost:27017/data';
MongoClient.connect(url, function(err, db) {
if(err) {
console.log('Unable to connect to server', err);
} else {
console.log('Connection established');
var collection = db.collection('compliments');
collection.find({}).toArray(function(err, result) {
if (err) {
res.send(err);
} else if (result.length) {
res.json(result); // problem here
} else {
res.send('No documents found');
}
db.close();
});
}
});
});
generate.jade
doctype html
html
head
title("Compliment Generator")
body
h1 !{title}
block content
h3.
!{compliment}
This is what it looks like on localhost:3000/generate
[{"_id":"570b50f8265f2536d2fd6ed6","type":"compliment","content":"You are absolutely gorgeous."},{"_id":"570b50f8265f2536d2fd6ed7","type":"compliment","content":"You are wonderful."},{"_id":"570b50f8265f2536d2fd6ed8","type":"compliment","content":"I could look at you all day."}]
How do I make it so that it only displays the "content"? Thanks!
If I understand correctly you only want the content to be returned from the query.
The below link should be of use:
https://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/
You essentially want to modify the query to only retrieve the "Content" part like so:
collection.find({}, { content: 1, _id:0 })
This will specify that you don't want to include the "_id" (which is included by default) and you do want to include the "content".

Fetching data from mongodb through nodejs and express to a html page

Basically, I want to show particular fields from "employees" collection into a html page. But even after searching a lot on web, I'm unable to do so.
Here is the route part from the server.js file:
app.get('/fetching', function(req, res){
connection.fetcher(function(data)
{
res.render("testing.html",data);
}
);
});
Now this is the part from connection.js file:
var fetcher= function(callback) {
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/HippoFeedo';
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);
// Get the documents collection
var collection = db.collection('employees');
collection.find({},function (err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
callback(result);
}
});
}
});
Now, findOne is working fine and returning the value to server.js file perfectly. But I need to use "find", so how to send the complete array to the server.js through callback?
And moreover, I need to send that retrieved data from server.js to a HTML file called testing.html through rendering and display it through angular js. Please explain a simple way to do so.
EDIT:
I got to know how to work with "find", I just used "toArray" alongwith "find" in function. And now, I'm able to return the value to server.js through call back. But the other question is still unsolved: How do I pass those values to the html page?
Using ejs, you need to set the view engine:
app.set('view engine', 'ejs');
Then get your data:
app.get('/employees',(req , res) =>{
db.collection('employees').find().toArray(function(err , i){
if (err) return console.log(err)
res.render('index.ejs',{employees: i})
})
});
The .ejs file would be like this:
employees
<ul class="employees">
<% for(var i=0; i<employees.length; i++) {%>
<li class="employees">
<span><%= " Nome: " +employees[i].name+"."%></span>
<span><%=" Address: " + employees[i].address%></span>
</li>
<% } %>
</ul>
Just a simple way using ejs. Hope it helps to clarify things.

Getting empty JSON from mongolab after GET request in node

My problem: I'm trying to HTTP.GET a random questionSchema from my database but it returns "". In my database (that is hosted in mongolab I have a few different collections, but in my questions collection I only have 3 different JSONs with 3 different questions.
I have a Schema that looks like this:
var questionSchema = new Schema({
description: String
});
module.exports = mongoose.model('Question', questionSchema);
In my routes.js I put the following:
app.get('/api/getrandomquestion', function (req, res) {
if (req.params.description) {
res.json(req.description);
} else {
res.json("");
}
});
I also have a service called QuestionService.js which is supposed to query the DB and give me back a random JSON document out of all (3) the documents that exist there. This is the code of the service:
var numberOfItemsToFind = 3;
Question.find({}, { '_id': 1}, function(err, data){
if (err) res.send(err);
var arr = shuffle.(data.slice(0));
arr.splice(numberOfItemsToFind, arr.length - numberOfItemsToFind);
var return_arr = [];
async.each(arr, function(item, callback){
Question.findById(item._id, function(err, data){
if (err) res.send(err);
return_arr.push(data);
callback();
});
}, function(err){
res.json(return_arr);
});
});
And lastly, I put these together with my questionCtrl:
controller('QuestionCtrl', function ($scope, $http, $modal) {
$http.get('/api/getrandomquestion').success(function (question) {
$scope.description = question.description;
});
});
I am using POSTMAN to make a HTTP.GET request to localhost:3000/getrandomquestion and I'm getting back just the "" as I stated.
Any help towards solving my problem (empty JSON instead of a real one) will be greatly appreciated!
The problem is in your routes.js:
app.get('/api/getrandomquestion', function (req, res) {
if (req.params.description) {
res.json(req.description);
} else {
res.json("");
}
});
req.params.description is undefined. So the if statement failed.
If param description is not necessary, You should probably define your GET API like this:
app.get('/api/getrandomquestion', function (req, res) {
QuestionService.getRandomQuestion(function(questions){
res.json(questions);
//res.send(questions);
});
});
Basically your backend receive a GET getrandomquestions API call, you just forward to fetch MongoDB using QuestionService.

How to push out requested data from mongodb in node.js

I'm working with Node.js, express, mongodb, and got stuck on this data passing between frontend and backend.
Note: code below is middleware code for front- and backend communication
Here I successfully get the input value from the frontend by using req.body.nr
exports.find_user_post = function(req, res) {
member = new memberModel();
member.desc = req.body.nr;
console.log(req.body.nr);
member.save(function (err) {
res.render('user.jade', );
});
};
Here is the problem, I need to use the input value I got to find the correct data from my database(mongodb in the backend) and push out to the frontend.
My data structure {desc : ''}, the desc is correspond to the input value so it should look something like this {desc: req.body.nr} which is probably incorrect code here?
exports.user = function(req, res){
memberModel.find({desc: req.body.nr}, function(err, docs){
res.render('user.jade', { members: docs });
});
};
Would love to have some help.
Thanks, in advance!
Have a look at this great tutorial from howtonode.org.
Because as you can see he uses a prototype and a function callback:
in articleprovider-mongodb.js
ArticleProvider.prototype.findAll = function(callback) {
this.getCollection(function(error, article_collection) {
if( error ) callback(error)
else {
article_collection.find().toArray(function(error, results) {
if( error ) callback(error)
else callback(null, results)
});
}
});
};
exports.ArticleProvider = ArticleProvider;
in app.js
app.get('/', function(req, res){
articleProvider.findAll( function(error,docs){
res.render('index.jade', {
locals: {
title: 'Blog',
articles:docs
}
});
})
});
Also make sure you have some error checking from the user input as well as from the anybody sending data to the node.js server.
PS: note that the node, express and mongo driver used in the tutorial are a bit older.

Categories