Client side can not take the json data - javascript

I have a nodejs server and the code that I have as below. I send an AJAX request and I want the server to send me a response of a json data. When I put res.write()("string data like hello hello") in the server code, client side can take the value of inside and I can see the value on the console. But I cannot get json value with this function. I tried res.end() and res.send() functions as well but it didn't work. How can I send the json value and the following client side code can take the value correctly?
Server side,
app.use('/', function(req, res) {
console.log("req body app use", req.body);
var str= req.path;
if(str.localeCompare(controlPathDatabaseLoad) == 0)
{
console.log("controlPathDatabaseLoad");
mongoDbHandleLoad(req, res);
res.writeHead('Content-Type', 'application/json');
res.write("Everything all right with database loading"); //I can get this message
//res.end(json) I can not get json message with this function as well
res.send("OK");
//res.send(JSON.stringify(responseBody)); I can not get json message
}
Client side,
function loadDatabaseData()
{
console.log("loadDatabaseData");
var oReq = new XMLHttpRequest();
oReq.open("GET", "http://192.168.80.143:2800/load", true);
oReq.setRequestHeader("Content-type", "application/json;charset=UTF-8");
oReq.onreadystatechange = function() {//Call a function when the state changes.
if(oReq.readyState == 4 && oReq.status == 200) {
console.log("http response", oReq.response);
console.log("http responseText", oReq.responseText);
}
}
oReq.send();
}

Related

How to fix not getting text response from Post request

I'm new to using nodejs and javascript so I'm sorry if I'm just doing something obviously wrong. I have a nodejs app I'm running and serves a html page. That html page can send Post requests using XMLHttpRequest. The request goes though and my node app calls the function that my request is meant to invoke. The problem is I want to get some data back from that request so I am trying to get that from the response to the request. The issue is I am getting an empty response and I do not know why.
Here is my request.
function SendCachedTriangulation(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('responseLog').textContent = "sent triangulation: " + this.response;
}
};
xhttp.open("Post", "/sendCachedTriangulation");
xhttp.setRequestHeader("Content-type", "application/json");
var text = '{ "data" : ' + '{ "someData":"' + '1' + '" } }';
xhttp.send(text);
return false;
}
The result I get from this is response is empty. It does update the element I am trying to update but it just says "sent triangulation: ".
On the nodejs side this is my code.
router.post('/sendCachedTriangulation', (req, res, next) => {
client.SendCachedTriangulation(() => {
res.status(200)
;}, req.body
);
res.status(200).message = "sent triangulation";
res.send();
});
Which this seems to be calling my function to send cached triangulation properly i just don't get that "sent triangulation" message.
What do I need to change to display that message in my HTML page?
Actually I understood your snippet. I also understand that is complicated at first time with Node, because is everything Javascript. Let me explain: in your HTML, think the request is OK, but actually have, let's say, two files: HTML file, that performs the request, and the node HTTP server, that responds the request. So I mean something like:
// /server/app.js
router.post('/sendCachedTriagulation', (req, res, next) => {
res.status(200).send("sent triangulation")
})
// /client/index.html
client.SendCachedTriangulation(/* do stuff */)

How to handle JSON data from XMLHttpRequest POST, using nodeJS

Overarching goal is to save some JSON data I create on a webpage to my files locally. I am definitely sending something to the server, but not in format I seem to able to access.
JsonData looks like:
{MetaData: {Stock: "UTX", Analysis: "LinearTrend2"}
Projections: [2018-10-12: 127.62, 2018-10-11: 126.36000000000001, 2018-10-10: 132.17, 2018-10-09: 140.12, 2018-10-08: 137.73000000000002, …]}
XMLHttpRequest on my webpage:
function UpdateBackTestJSON(JsonUpdate){ //JsonUpdate being the JSON object from above
var request = new XMLHttpRequest();
request.open('POST', 'UpdateBackTestJSON');
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
// request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
request.onload = function() {
console.log("Updated JSON File");
};
console.log("about to send request");
console.log(JsonUpdate);
request.send(JSON.stringify(JsonUpdate));
}
and I handle posts on my server (rather carelessly I realize, just going for functionality as a start here)
var http = require('http')
, fs = require('fs')
, url = require('url')
, port = 8008;
var server = http.createServer (function (req, res) {
var uri = url.parse(req.url)
var qs = require('querystring');
if (req.method == 'POST'){
var body = '';
req.on('data', function (data){
body += data;
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6){
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
req.connection.destroy();
}
});
req.on('end', function () {
var POST = qs.parse(body);
console.log(POST); // PARSED POST IS NOT THE RIGHT FORMAT... or something, idk whats going on
UpdateBackTestData(POST);
});
}
function UpdateBackTestData(TheJsonData){
console.log("UpdateBackTestData");
console.log(TheJsonData);
JsonUpdate = JSON.parse(TheJsonData);
console.log(JsonUpdate["MetaData"]);
//var Stock = JsonUpdate["MetaData"]["Stock"];
// var Analysis = JsonUpdate["MetaData"]["Analysis"];
fs.writeFile("/public/BackTestData/"+Analysis+"/"+Stock+".json", TheJsonData, function(err){
if(err){
console.log(err);
}
console.log("updated BackTest JSON!!!");
});
}
Most confusing to me is that when I run this, the Json object Im am trying to pass, does go through to the server, but the entirety of the data is a string used as a key for a blank value in an object. when I parse the body of the POST, I get: {'{MetaData:{'Stock':'UTX','Analysis:'LinearTrend2'},'Projections':[...]}': ''}. So my data is there... but not in a practical format.
I would prefer not to use express or other server tools, as I have a fair amount of other services set up in my server that I don't want to go back and change if I can avoid it.
Thanks for any help

Node.js Doesn't Recognize Ajax Request

I am trying to make a private page dedicated to an Ajax request. Here is the simple request.
window.onload = loaded;
function loaded(){
var xhr = new XMLHttpRequest();
xhr.open('GET', '/data_annotations', true);
xhr.onload = function(){
if(this.status == 200){
var data = xhr.responseText;
console.log(JSON.parse(data));
} else {
console.log("Rip");
}
}
xhr.send();
//httpreq.abort();
}
Here is the node.js that it's running off of:
...
app.get('/', function(req, res, next){
console.log("Connected Successfully.");
res.render('home');
});
app.get('/data_annotations', function(req, res, next){
if(req.xhr || req.headers.accept.indexOf('json') > -1) {
const mc = mongo.MongoClient;
const url = 'mongodb://localhost:27017/';
const dbName = 'practiceMDB';
console.log("Got Data Annotations.");
mc.connect(url, { useNewUrlParser: true }, (err, client) =>{
if(err){
console.log(err);
} else {
const db = client.db(dbName);
data = db.collection('DataAnnotations');
data.find({}).toArray(function(err, data){
res.send(data)
});
client.close();
}
});
} else {
res.redirect('/');
}
});
app.listen(port, function(){
console.log('Server Started on Port '+port);
});
I only want /data_annotaion to run if it's from the Ajax request. If a user types in /data_annotations in the url, it should redirect them to the home page. When I ran this I got these results:
Server Started on Port 3000
Connected Successfully.
Connected Successfully.
This is indicating (to me) that the ajax request isn't registering as an ajax request, and is registering as a normal request. Further, I am getting this error:
Uncaught SyntaxError: Unexpected token < in JSON at position 0
I believe it is due to the redirection. The Ajax request gets redirected, it takes the response of the home page and is unable to parse it (I believe this to be happening because it cannot parse HTML text or string text - don't quote me on that). How do I get Node JS to register my Ajax request?
PS: I looked at this answer to determine if a request is Ajax or not, but it always determines my requests as not Ajax: https://stackoverflow.com/a/28540611/6804700
First thing - In your client-side code you need to set the accept header, because that is what you are looking for in your server side code.
xhr.setRequestHeader("accept", "application/json");
Second you can use the following code to return the data as json in your server side code
res.json(data);
Another comment. It is bad practice to change the result type or redirect in an API. Your url is either returning JSON or redirecting to and HTML page which means the result is not consistent.

How to properly do a server side api request?

I am very new with node js and decided to learn how to secure api keys, i've looked everywhere but can't find a example. But i found some that suggest the only way is to do a server side api request.
I am using openweathermap api for this code, i get the expected data back as a response in chrome network tab but i have questions regarding it.
How do i use the response data (e.g getting the current weather, temp) ?
Is this the proper way on doing a server side api request in node.js?
http.createServer(function(req, res) {
if (req.url === '/') {
res.writeHead(200, {"Content-Type": "text/html"});
fs.createReadStream(__dirname + '/index.html').pipe(res);
} else if (req.url === '/getweather') {
var weatherApiURL = 'https://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=<API KEY>';
request(weatherApiURL, function (error, response, body) {
if (error) {
res.writeHead(500, 'Weather API request failed', {'content-type': 'text/plain'});
res.end();
} else {
res.writeHead(200, {'content-type': 'application/json'});
res.end(body);
}
});
} else {
res.end('not found')
}
}).listen(8080);
Front:
function requestWeatherData() {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/getweather', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function () {
console.log(this.responseText);
};
xhr.send();
};
Thank you in advanced!!
Part 1: How to use the data.
The first thing you'll want to do is to check whether the request succeeded
if (this.status !== 200) {
// The request did not work.
throw new Error('Cannot use data.');
}
Once the requset status has been verified you need to 'parse' the response.
const weatherData = JSON.parse(this.responseText);
// Lets see the js object:
console.log(weatherData);
Now you can do whatever you need with the data.
The full example:
function requestWeatherData() {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/getweather', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function () {
if (this.status !== 200) {
// The request did not work.
throw new Error('Cannot use data.');
}
const weatherData = JSON.parse(this.responseText);
// Lets see the js object:
console.log(weatherData);
};
xhr.send();
};
Part 2: Is there a proper way of doing this?
Now, I don't not know enough about this to say definitely, however, here are some concerns that you may want to think about.
Most APIs have rate limits, meaning you probably want to try to 'cache' the requests somewhere to reduce the need to 'poll' the APIs
Other people could use your exposed url in their application.
Writing all of the routes as you are currently will become a real headache for larger applications, I can recommend express from experience for small to medium applications.

POST data from a client javascript page to a node server

Is it possible to POST data from a client javascript page to a node server (server.js) using an AJAX XMLHttpRequest()? What I am looking for is javascript code that will receive the data on the node server, specifically the values for member_nm ("newName") and member_email ("mail#google.com"). I control the server. I also understand that I can also use GET to send the text values by means of a querystring. Below is the request that is sent from the client javascript page by means of an event handler:
document.getElementById("btnAddMember").addEventListener("click", function()
{
var request = new XMLHttpRequest();
var path = "/Users/Admin/WebstormProjects/projectName/server.js";
request.onreadystatechange = function()
{
if ( request.readyState === 4 && request.status == 200 )
{
request.setRequestHeader("Content-Type", "text/plain; charset=UTF-8");
request.open("POST", path, true);
request.send("member_nm=newName&member_email=mail#google.com");
}
};
});
You need to setup your server to accept this post request, the easiest will be to use Express with bodyParser middleware, like this :
var express = require('express');
var server=express();
var bodyParser= require('body-parser');
server.use(bodyParser.json());
server.post('/', function(req, res){
if(req.body){
// get the params from req.body.paramName
}
});
server.listen(8222, function(){
console.log('listening for requests ..')
});
In your client code change the 'path' to point to the server url:port, and I will put these outside of the onReadyStateChange:
request.setRequestHeader("Content-Type", "text/plain; charset=UTF-8");
request.open("POST", path, true);
request.send("member_nm=newName&member_email=mail#google.com");
This is a working solution on how to POST variables from a client javascript file to a Node server using Express. The POST is initiated on the client by means of an event handler, btnAddMember. txtName.value and txtMembershipType.value contain the values to be posted. Note the syntax that is necessary to parse the values correctly. member_nm and member_type will be used to reference the properties on the Node server. First the client javascript:
document.getElementById("btnAddMember").addEventListener("click", function()
{
var request = new XMLHttpRequest();
var path = "http://0.0.0.0:0000"; // enter your server ip and port number
request.open("POST", path, true); // true = asynchronous
request.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
var text= '{"member_nm":"' + txtName.value + '","member_type":"' + txtMembershipType.value + '"}';
request.send ( text );
});
Next is the server side code. Note that bodyParser must now be added to your project as a node_module. This can be done through the node program manager (npm). The POST statement basically parses the req.body from a JSON format to a javascript object format using a variable called 'member'. The code then logs the posted values for the two variables, member_nm and member_type. Finally a response status is sent to the client if the POST is successful.
var bodyParser = require("body-parser");
...
app.use(bodyParser.text({ type: "application/json" }));
...
// receive the POST from the client javascript file
app.post("/", function (req, res)
{
if (req.body)
{
var member = JSON.parse( req.body ); // parse req.body as an object
console.log("member_nm: " + member.member_nm );
console.log("member_type: " + member.member_type );
res.sendStatus(200); // success status
}
else
{
res.sendStatus(400); // error status
}
});

Categories

Resources