How to pass data from node js to html.? - javascript

How can I simply pass a variable from node js to html and display it in the page?
What is the simple mechanism.
I am trying to develop a simple to-do list using node js

There are two approaches here you can use to view data from node( server side ) to html:
1- You could create a file in node which return data in json, then from JQuery you could do an ajax call this page and replace parts of the HTML with it.
Sample code in node js:
var usersFilePath = path.join(__dirname, 'users.min.json');
apiRouter.get('/users', function(req, res){
var readable = fs.createReadStream(usersFilePath);
readable.pipe(res);
});
Ajax call:
$.get( "/users", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
2- You could use express with Jade ( I recommend
http://expressjs.com/ )
Here is my blog on how to get started with node.js Click Here
I created a starter kit for nodejs If you are interested Click Here

Establish a route and use res.send method to respond with html content. The html content can use es2015 templates to include a variable in response. So it would look like:
const name = 'pradeep';
res.send(`hello ${name}`);

Try this, it may help you.
The Following function will bind your dynamic data to html
function doDataBinding(data, databindings){
for(var prop in databindings)
if( databindings.hasOwnProperty(prop) )
data = data.split('${'+prop+'}').join(databindings[prop]);
return data;
}
Sample request to verify dynamic data binding is as follows
app.use('/*', function(req, res){
//sample binding data
var dataToBind = { 'msg' : 'You\'ve been logged out successfully.' , 'error' : 'The username and password that you entered don\'t match.' };
res.writeHead(200, {
"Content-Type": "text/html"
});
fs.readFile( __dirname + '/login.html', 'utf8' ,function(err, data) {
if (err) throw err;
data = doDataBinding(data,dataToBind);
res.write(data);
res.end();
});
});
Try with login.html which is having ${msg} and ${error} data bindings.

Related

post request only posting [object Object]

So I'm new to post/get requests and this is really my first time touching it. I'm having issues where while data is posted from my client side to server side and saved to my database, no matter what it just posts: "[object Object]"
Server side code:
//Recieve new help message
app.post("/postNewHelp", function(data){
var newHelp = data;
console.log(newHelp);
//Upload to database
pingdb.all(`UPDATE userHelp SET privateMessage = "${newHelp}"`);
});
Client side:
//send new help message
function sendNewHelp() {
var newHelpMessage = document.getElementById("userHelpSetting").innerHTML;
console.log (newHelpMessage);
//Send to serverside
$.post("/postNewHelp", newHelpMessage), function(data){
console.log(data);
}
alert("Done! your changes should now be in effect.");
}
Any help is appreciated, thanks!
Try to name your data like that.
$.post("/postNewHelp", {helpText:JSON.stringify(newHelpMessage)}), function(data){
console.log(data);
}
And in your server side you can find your date like that.
var helpText = data.helpText
But, while you are using jQuery, don't hesitate to use that in your client side.
var newHelpMessage = $("#userHelpSetting").text();
Please feel free to read about JSON Stringify and JSON parse
Check the client side code. If possible send the parameter as json object as below
function sendNewHelp() {
var newHelpMessage = document.getElementById("userHelpSetting").innerHTML;
console.log (newHelpMessage);
//Send to serverside
$.post("/postNewHelp", {"help": newHelpMessage}, function(data){
console.log(data);
alert("Done! your changes should now be in effect.");
});
}
Now on the server side
//use the body parser
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
extended: true
}));
app.post("/postNewHelp", function(req, res){
var newHelp = req.body.help;
console.log(newHelp);
//Upload to database
pingdb.all(`UPDATE userHelp SET privateMessage = "${newHelp}"`);
});

Get request from client to Node server with objects

How do I send an object from the client to the Node server.
My Object looks like this:
var myobj = {};
myobj.title = "title1";
myobj.message = "message1";
I simply want to send it to the server to save it to the database with mongoDB. But when I try to send it and look at the request, only unreadable text comes out.
This is the code on the client:
$.get( '/createA',myobj, function(data) {
console.log(JSON.parse(data));
});
This is my server code:
router.get('/createA', function(req, res, next) {
let gelp = req._parsedOriginalUrl.query;
let res1 = gelp.replace(/%22/g, "'");
var test = JSON.parse(res1);
});
I tried to format the string with the .replace() function and parse it back to JSON but it doesn't work.
Is there any other way I can get an object from client side JavaScript to Node and work with that object there?
see: https://api.jquery.com/jquery.post/
also just console.log or do res.send('it worked!') to test these things out for the first time instead of trying to modify things before you know the backend is receiving it.
$.post("/createA", myobj, function( data ) {
console.log( data.title );
console.log( data.message );
}, "json");
and try this first.
router.post('/createA', function(req, res) {
res.send('it worked!')
});
after that works, you can try to modify and send back the object. like so
router.post('/createA', function(req, res) {
var data = {}
data.title = req.body.title.toUpperCase()
data.message = req.body.message.toUpperCase()
res.send(data)
});

In Node.js, how to update different components of a page in different frequency?

I'm trying to build a real time webpage to show some real time statistics. This webpage has 12 components. I'm using Ajax in SetTimeout to update each component. Since I'd like to update each component in different frequency, I write a setTimeout function for each component and gives each component a link (defined in "main.js"). Looks like:
(function poll() {
setTimeout(function() {
$.ajax({
url: url1,
type: 'GET',
success : function(info){
var object = document.getElementById("1");
object.textContent = info;
}, complete: poll });
}, 5000);
})();
...
...
(function poll() {
setTimeout(function() {
$.ajax({
url: url12,
type: 'GET',
success : function(info){
var object = document.getElementById("12");
object.textContent = info;
}, complete: poll });
}, 10000);
})();
And in my "server.js", I hope to connect to database only once and then render different components. The configuration of the database will rely on the link so I organize the app like this:
app.get('/:A/:B', function(req,res){
var A= req.params.A;
var B = req.params.B;
var config = something relies on A and B
var client = new pg.Client(config);
client.connect(function(err){
if (err) {
console.log("Error occurred when try to connect the database",err);
}
else {
res.sendFile(__dirname + '/public/main.html');
app.get('/main.js', function(req,res){
res.sendFile(__dirname + '/public/main.js');
});
app.get('/url1',function(req,res) {
//query database and send the data url1 needs
});
...
...
app.get('/url12',function(req,res) {
//query database and send the data url12 needs
});
})
I want to ask if writing "app.get()" within "app.get()" like the code above is good practice. If not, how can I keep a global connection to the database and use it for different components? Also, is there any improvement I can make to this web app? I'm quite new to Node.js
If I had to do this with callbacks instead of promises, this is how I would do it on Server side.
first, I would use your endpoint to get the client, but would put it in a module internal variable, and still send a response if I failed to connect to DB.
var db=null;
app.get('/:A/:B', function(req,res){
var A= req.params.A;
var B = req.params.B;
var config = something relies on A and B
var client = new pg.Client(config);
client.connect(function(err){
if (err) {
console.log("Error occurred when try to connect the database",err);
res.status(503).send("Error connecting to database);
}
else {
db = client;
res.sendFile(__dirname + '/public/main.html');
}
}
}
Then, I would write a function that would reuse that DB if it exists:
function usingDatabase(req,res,next){
if(db) {
req.db=db;
next();
}
else {
res.status(400).send("Bad request. open the DB first by calling /:A/:B");
}
}
finally I'd use it like this:
app.get('/main.js', function(req,res){
res.sendFile(__dirname + '/public/main.js');
});
app.get('/url1',usingDatabase, function(req,res) {
// db is in req.db;
//query database and send the data url1 needs
});
...
...
app.get('/url12',usingDatabase,function(req,res) {
// db is in req.db;
//query database and send the data url12 needs
});

NodeJS GET request not working with AngularJS

I have this web app that is for sharing photos.
Now I have this route that is supposed to return the photos of all the users from the following array.
Route:
router.get('/getphotos',function(req, res){
var reqPhotos = [];
console.log( "\n" + req.body.username + "\n");
try{
for(x =0; x < req.body.following.length; x++){
reqPhotos.push({username: req.body.following[x].username});
}
}
catch(err){
console.log(err);
}
Photo.find({username: reqPhotos}).exec(function(err, allPhotos){
if(err){console.log(err);}
else{
res.json(allPhotos);
}
});
});
I have found out that the req.body.following was undefined. This is how I was calling it using angular:
$scope.getPhotos = function(){
if($scope.identification){
flng = angular.copy($scope.identification.following);
flng.push($scope.identification.username);
var data = {username: $scope.identification.username, token: $scope.identification.token, following: flng}
//IDENTIFICATION HAS ALL THE INFO.
$http.get('/users/getphotos', data).success(function(response){
$scope.photos = response;
});
}
}
Why does this happen and how to fix it?
Thanks!
Not sure about the server side, but I see two problems in the angular code. You cannot pass a body when doing an HTTP GET request. Try to pass any necessary data through the url.
Also, the actual data that is returned, will be in response.data. Do something like this:
var urlData = ""; //add any url data here, by converting 'data' into url params
$http.get('/users/getphotos/' + urlData).then(function(response){
$scope.photos = response.data;
});
For constructing the urlData, have a look at this question.
Of course, you will have to adjust the server so it reads the data from the url, rather than from the body.
I don't know what the Content-Type in request request header, is that application/json or application/x-www-form-urlencoded or other. Every content type have to be treated differently. If you use expressjs, try using multer to handle request with multipart-form content type, I usually use it in my application.
$http doesn't take a 2nd parameter for a data object in GET method. However, $http does accept a data object as the 2nd parameter in POST method.
You'll need pass it as the params property of the config object and access it in your req.query in node:
$http.get('enter/your/url/', { params: data})

Node Express pass variable from client to server

I am trying to return value from an input box to a variable in route, by taking this source as a reference but am stuck, in the example author is searching a keyword, constructing a url using this keyword, and returning a body response.
My use case is a little different I need user to provide a url as a string in search box, which I would then pass to my request function to spit response body
Current app.js (server-side)
app.get('/searching', function(req, res){
// input value from search
var url = req.query.search;
console.log(url); // prints value
request({ uri: url}, function (error, response, body) {
if (!error) {
content = body;
console.log(content);
} else {
console.log('Oops! Error when contacting slack.com');
}
});
res.send(content);
});
main.js (client-side)
$(function(){
$('#submit').on( 'click', function () {
var sSearch = $('#search').val();
var parameters = { search: sSearch };
$.get( '/searching',parameters, function(data) {
$('#results').html(data);
});
});
});
I realize /searching in both above files must be replaced because currently its trying to 'search' the user entered url value as a query string, so if I enter "https://google.com" in the text box the application tries to search:
http://localhost:3000/searching?search=https%3A%2F%2Fgoogle.com
instead I need it to pass this url as is to the request function so that I can print the body response, which in this case would be the page's source code. But am not sure how should I proceed
index.jade (template)
extends layout
block content
input#search(type="search", placeholder="Enter Keyword")
button#submit(type='submit',class='btn btn-success') Search
h2#results
script(src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js")
script(src="/javascripts/main.js")
How should I format so that I can pass the variable from client to server and then send it back to client after processing? Any help is appreciated.
In the app.js you are making a async http call, but the response is sent before the http callback is invoked. Just move the res.send(content); inside the call back
app.get('/searching', function(req, res){
// input value from search
var url = req.query.search;
console.log(url); // prints value
request({ uri: url}, function (error, response, body) {
if (!error) {
content = body;
console.log(content);
} else {
console.log('Oops! Error when contacting slack.com');
}
res.send(content);
});
});
i see ajax request in your client code , so in your server code, try to response something like this :
res.status(200).json(content)
in your client code ,check if the content is there (console.log(data) before $().html(data)... )
PD : request is async , so you have to response inside request callback.

Categories