Sam kh Sam kh - 2 months ago 7
JSON Question

Understanding routing from client side (javascript) to server side (node.js)

I'm new at web apps and at the moment I'm trying to wrap my head around routing from client side to server side and back. I ran in to a problem where I was doing xmlhttprequest on my client side to get a json, which was working. But now that im not running locally none of the GETS are working. So I figured I have to do routing to server side, do the request() to get the json, which I can.

But now what I don't understand is how to pass that json back to client side to use the function there, since all my functions that use this json are there. Is this possible? or do I have to do everything server side now?

server side

server.get('thankyou.html/something', function(req, res) {

var options = {
url: 'https://**.***.**.**:****/****/*******/',
rejectUnauthorized: false,
method: 'GET'

request(options, function (error, response, body) {
if (error) console.log(error);
else displaytable(body);//<------- clientside funtion

client side

var uri = 'thankyou.html/something';

function addTable() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && (xhr.status == 201 || xhr.status == 200)) {
// var json = JSON.parse(xhr.responseText);

};"GET", uri, true);

I think I'm not doing the routing right either.


What's the expected flow here? client -> your server @ thankyou.html/something -> some other server url (the one you have censored) -> response back to your server -> response back to client -> client uses response to display table?

Either way, you definitely can't call client functions from your server. Not like that, anyways. You'll need to return the body with something like res.json(body) (what routing / server library are you using?), and then parse the xhr.responseText, like your commented-out line was doing. Then you'll have the json on the client, and can continue as expected.

Make sure if your request call returns an error that you pass the error through to the client as well, or it will hang until timeout.