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 */)
Related
I'm making a web application with Flask. The user submits a form which is passed to server. The value is passed to a python script I wrote that checks to see if a username is taken on a number of web forums.
As the results come in they are passed back to the page with AJAX. I want to update the webpage as the data comes in. I understand that websockets is probably more efficient, but this is just for practice and I want to learn how to do it with polling.
main.py:
#app.route('/search', methods=['GET', 'POST'])
def search_form():
#print(request.form)
x = request.form['id']
a = Vbulletin(x)
def result_gen():
return a.reg_ver()
result_gen()
def generate_resp():
with app.app_context():
for text in result_gen():
print(text)
text2 = json.dumps(text)
#print(text2)
yield (text2)
sleep(1)
return app.response_class(generate_resp(), mimetype='application/json')
app.run()
forumsearch.js:
$(document).ready(function(){
$("#submit").on('click',function(e){
e.preventDefault();
req = $.ajax({type: "POST",
url: "/search",
data: { id: $("#searchinput").val()},
});
req.done(function(temp){
var latest = document.getElementById('latest');
var output = document.getElementById('output');
var xhr = new XMLHttpRequest();
xhr.open('GET', '/search');
xhr.send();
var position = 0;
function handleNewData() {
var messages = xhr.responseText.split('\n');
messages.slice(position, -1).forEach(function(value) {
latest.textContent = value;
var item = document.createElement('li');
item.textContent = value;
output.appendChild(item);
});
position = messages.length - 1;
}
var timer;
timer = setInterval(function() {
handleNewData();
if (xhr.readyState == XMLHttpRequest.DONE) {
clearInterval(timer);
latest.textContent = 'Done';
}
}, 1000);
});
});
});
The issue i'm having is that the results are showing up from the POST requests in the browser when I look at the response in the network tab, but it is not being updated on the webpage. There a couple of things I see that could be the issue, but I am unsure how to proceed.
The first is that the XHR 'GET' request is never sent. The 'POST' request is sent and the response is coming in to the client, but the 'GET' request after it is never sent.
Maybe I'm not understanding polling, but don't i need to make a GET request to poll the server? Or do need to just handle the POST request?
Another problem I see is that response that I'm getting from 'POST' request has a syntax error.
The response is this:
"https://www.bimmerboost.com/register.php , user found!!! I SAID USER FOUND!!!""http://www.vbforums.com/register.php , user found!!! I SAID USER FOUND!!!"
and error in firefox is this:
SyntaxError: JSON.parse: unexpected non-whitespace character after
JSON data at line 1 column 80 of the JSON data
How can I fix this error, and what do I need to change to get the server response to show up in html?
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
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.
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();
}
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
}
});