Get request from client to Node server with objects - javascript

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)
});

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}"`);
});

Sending data from NodeJS to the client by using Ajax calls

I increase a value at the server by running an Ajax call and want to update my UI after doing this
function increaseHitpoints(){
$.ajax({
type: 'GET',
url: 'http://localhost:8888/incHp/2312'
}).done(function (data) {
$("#txtHitpoints").html(data);
});
}
In my app.js I read a JSON file, manipulate the value, write it back to the file and return it to the client
app.get('/incHp/:id', function (req, res) {
var database = './database.json';
fs.readFile(database, 'utf8', function (err, data) { // read the data
var json = JSON.parse(data);
var users = json.users;
var hitpoints;
users.find(u => {
if (u.id === Number(req.params.id)) { // get the user by id
u.hitpoints++;
hitpoints = u.hitpoints;
}
});
json = JSON.stringify(json);
fs.writeFile(database, json, (err) => { // update the JSON file
// -> missing part here <-
});
});
});
what do I have to pass into the missing part if I want to return the new value? The new value would be hitpoints
I tried res.send(hitpoints); but it seems this function wants to return a status code, not a value.
If you send a numerical value, it will be observed as an HTTP response code
https://expressjs.com/en/api.html#res
But you can send your hitpoints as a string res.send(hitpoints.toString())or as json res.send({hits: hitpoints});
Depends on what format you want your response to be. I prefer using JSON. So in JSON case you would do this:
fs.writeFile(database, json, (err) => {
res.status(200).json({yourKey: yourValue});
});
Then you can access the JSON object in your frontend:
$("#txtHitpoints").html(data.yourKey);

How to pass data from node js to html.?

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.

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})

Sails.js Sending json object returned in https.request to the view

Just learning Sails.js so go easy on me.
I have queried an XML service and successfully jsonified it using xml2js
var req = https.request(options, function(res) {
var xml = '';
res.on('data', function(chunk) {
xml += chunk;
});
res.on('end', function () {
var result = parseString(xml, function (err, result) {
console.log(JSON.stringify(result)); // Position 1
});
return result;
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write(data);
var result = req.end();
console.log('Result: ' + JSON.stringify(result)); // Position 2
res.view({ message : 'hello', result : result });
The view is loading fine, and <%= message %> outputs hello. Great.
Position1 console.log is returning the stringified json object - Great.
Position 2 consile.log is returning Result: true - Not good.
I need to be able to get that json data to my view for parsing. How do I do this?
It looks like you're assuming that calling req.end() will give you the response from the https.request you started above. There are a couple of things wrong with that:
req.end() is used to finish writing to an open request, not to get a response. According to the docs, the return value is unspecified.
The https.request call is asynchronous; even if req.end() worked like you want it to, the response wouldn't have come in by the time you call it.
The solution is to put your response code (i.e. your res.view) inside the handler for the end event that you've already written. I'd also recommend refactoring your code to use different variable names for the remote request / response so that they don't collide with the req and res variables in your controller action. The whole thing would then be something like:
myAction: function (req, res) {
// Not sure how you're setting options, so just an example
var options = {url: 'http://example.com', ...}
var request = https.request(options, function(response) {
var xml = '';
response.on('data', function(chunk) {
xml += chunk;
});
response.on('end', function () {
var result = parseString(xml, function (err, result) {
return res.view({ message : 'hello', result : JSON.stringify(result)});
});
});
});
request.on('error', function(e) {
console.log('problem with request: ' + e.message);
res.serverError(e);
});
}
You might also look into using something like the Request module to simplify your external request; it would save you from having to write event handlers for data and end.
if you want to pass json to some javascript variable:
var clientJsonVar = <%- JSON.stringify(serverSideJson)%>

Categories