Send obj with page render in expressjs mongoose - javascript

As a follow up to the this post:
mongoose find all not sending callback
I am trying now to send a Object along with a page in my nodejs/expressjs app instead of sending the JSON data as the response only.
The route for my page
//Get latest listings page
router.get('/latest', function (req, res) {
var rL = Request.getAllRequestListingsCb();
res.render('latest');
});
And as per the linked post, it suggest the following below but I need to return a JSON to my route, not send it direct to the client.
//Find all.
module.exports.getAllRequestListings = function (response) {
var query = {};
Request.find(query, function (err, docs) {
response.send(docs);
});
};
Have attempted to use a promise but my rL var keep returning as undefined so the Promise never gets get as "done" and i believe to be because I have not changed it correctly so now am here.
(The end goal is to render a table within the latest page using "handlebars" to display the data from the Json send with the page.)

You should be using proper callback chaining as find method is asynchronous.
//Find all.
module.exports.getAllRequestListings = function (callback) {
var query = {};
Request.find(query, callback);
};
Router
//Get latest listings page
router.get('/latest', function (req, res) {
Request.getAllRequestListingsCb(function (err, docs){
res.render('latest', { rL: docs });
});
});

Related

How to render view template using node js express

I create an Ajax request (below) which passes data to the server with the information I need.
function verify(key) {
$.ajax({
async: true,
type: 'GET',
url: '/zonepass/'+key,
data: {
'zone_key': key
},
success: function(res){
//alert('Sent a text message successfully to ' + res);
}
});
}
I handle the Ajax request on the server side where I use the passed in data to query my Firebase DB to get other relevant information.
I then try to render the view page that I want to navigate to using res.render('verify',{zone: obj, key: zone_key}) where verify is another .ejs file that I want to navigate the user to and the JSON object is the data that I want to pass to that template.
My code is not rendering the view page and I'm not sure why. I console logged all the data on the server and all the data is being pulled properly but then my view page never navigates to the verify ejs file...
app.get('/zonepass/:id', function(req,res) {
var zone_key = req.param('zone_key');
var zone_obj = firebase.database().ref('zones').child(zone_key).once('value').then((snap) => {
obj = snap.val();
res.render('verify',{zone: obj, key: zone_key});
});
});
res.render will not work with an ajax request, response from ajax call is returned and accessible inside the success function, but res.render will not work also res.redirect will not work with ajax request.
So you need to submit your request using a form or redirecting on frontend to that route, which is technically also a get request but without ajax example:
Using only HTML:
Verify
Using javascript:
function verify(key) {
window.location.href= "/zonepass/"+ <your id> + "?zone_key=<your zone key>"
}
Also in your NodeJS route you can access id using req.params.id and zone_key using req.query.zone_key, so your server code will be:
app.get('/zonepass/:id', function(req,res) {
var id = req.params.id;
var zone_key = req.query.zone_key;
var zone_obj = firebase.database().ref('zones').child(zone_key).once('value').then((snap) => {
obj = snap.val();
res.render('verify',{zone: obj, key: zone_key});
});
});
BTW you will need to handle inside the verify view, if the key is not verified, example you show an error or message in verify view, that the key is not correct ... or any message related to your logic

getting progress callback with jQuery and node express server

I am trying to grasp using node express server and jQuery.ajax() in tandem. I have created a code repository with the following structure:
/
|-public
| |-index.html
|-server.js
My index page has the following JS snippet in it:
var successHandler = function (data, status, jqXHR) {
console.log('success')
};
var failHandler = function (jqXHR, status, errorThrown) {
console.log('fail')
};
var progressHandler = function () {
console.log('progress')
};
var ajaxConfig = {
url: 'http://localhost:4444/test',
type: 'GET'
};
$.ajax(ajaxConfig).then(successHandler, failHandler, progressHandler);
the server-side code is defined as such:
const express = require('express')
const app = express()
const sleep = require('sleep')
app.get('/test', function (req, res) {
console.log('/test method called!');
sleep.sleep(3);
res.status(202).send({"thing":"stuff"})
})
app.post('/test', function(req,res){
res.status(202).send('ok')
})
app.use(express.static('public'))
app.use(express.static('node_modules/jquery/dist'))
app.listen(4444, function () {
console.log('Running on localhost:4444!')
})
The thing that I want to accomplish is to get some hits on the progress handler, just to get it to write data in the console.
According to this page, I need to use the deffered.notify() method to trigger the handler but I have no idea how to get to the deffered object. I tried saving the return value of $.ajax() but that doesn't seem to have the notify() method since it is a jqXHR object.
It is my understanding that I need to have a progress handler defined on the server-side (the post handler for the /test route) that gets called to get to the current status of the pending task. Don't think making a new ajax request is the way to go, but I might be wrong. I have also found some articles that utilize the setTimeout method, My guess is that it gets used in order to repeatedly call the endpoint that gives status info.

How to use an asynchronous response value in an `app.get` callback

I want to use flickrapi (https://www.npmjs.com/package/flickrapi) package. I need to authorize it:
Flickr.tokenOnly(flickrOptions, function(error, flickr) {
//I need this flickr variable
});
and I want to use this flickr variable in my express code
app.get('/', function (req, res) {
//do something with flickr
});
How should I do it?
Modular approach:
Put your flickr connectivity code separate:
flickr-public.js
var Flickr = require("flickrapi"),
flickrOptions = {
api_key: "API key that you get from Flickr",
secret: "API key secret that you get from Flickr"
};
module.exports = (function(){
Flickr.tokenOnly(flickrOptions, function(error, flickr) {
//handle error here
console.log('Flickr Object Obtained');
return flickr;
});
})();
Note: Better instantiate the flickr object in your app.js file.
So that the object gets created immediately when server starts. As this flickr object is for public API only and does not need authentication again and again.
You can instantiate the flickr object by simply requiring it in app.js file:
require('./flickr-public');
Now Simply access flickr object anywhere by simply requiring it.
routes.js
const flickr = require('../path-to/flickr-public');
app.get('/', function (req, res) {
//use flickr object to perform actions.
});
Explanation:
From the node.js documentation:
Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.
Multiple calls to require('foo') may not cause the module code to be executed multiple times.
Just put it inside your get
app.get('/', function (req, res) {
Flickr.tokenOnly(flickrOptions, function(error, flickr) {
//do something res.status(200).send('what you want here');
});
});
use it directly inside your route callback
app.get('/', function (req, res) {
Flickr.tokenOnly(flickrOptions, function(error, flickr) {
//call someother method to get photos etc. and finally call res.send()
res.send(photos); // where photos is obtained from flickr or anything you can pass which should be response of you request.
});
});

What javascript library sets the _parsedUrl property on a request object

I am working with node/express/passport/ looking at code that attempts to use a request like:
req._parsedUrl.pathname;
I cannot figure out where this variable is coming from. Is this a canonical variable name that is set in a common .js library? It doesn't seem exposed in any headers.
req._parsedUrl is created by the parseurl library which is used by Express' Router when handling an incoming request.
The Router doesn't actually intend to create req._parsedUrl. Instead parseurl creates the variable as a form of optimization through caching.
If you want to use req._parsedUrl.pathname do the following instead in order to ensure that your server doesn't crash if req._parsedUrl is missing:
var parseUrl = require('parseurl');
function yourMiddleware(req, res, next) {
var pathname = parseUrl(req).pathname;
// Do your thing with pathname
}
parseurl will return req._parsedUrl if it already exists or if not it does the parsing for the first time. Now you get the pathname in a save way while still not parsing the url more than once.
You can write a middleware to handle then set properties for req.
var myMiddleWare = function () {
return function (req, res, next) {
req._parsedUrl = 'SOME_THING';
next()
}
};
app.get('/', myMiddleWare, function (req, res) {
console.log(req._parsedUrl); // SOME_THING
res.end();
})
Express middleware document in here

Node.js and SQLite3

I am want to create web server that will return data for my mobile app. I use Node.js for server and SQLite3 for database. I created method that must return data from sql, but I don't know how to do it correctly. As I know all methods from SQLite lib are async so I have no idea how to do sync request for DB. I tried this way:
app.get('/getAllLeagues',function (req, res) {
console.log("get")
var obj = db.all("SELECT name FROM Leagues")
})
But seems that obj is still the same as db object
I'm assuming that your app is an express server instance or similar. The database query function takes a callback function that is called once the queried rows are ready or an error is found.
app.get('/getAllLeagues',function (req, res) {
console.log("get")
var obj = db.all("SELECT name FROM Leagues",
function(err, rows) {
res.type('json');
res.send(rows);
});
});
For simplicity, there is no error handling. It is better to try..catch a similar request to avoid crashing your app in case the database or the table is not found.

Categories