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

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);
displaytable(json);
}
};
xhr.open("GET", uri, true);
xhr.send();
}
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.

Related

Receiving HTTP POST request sent by frontend JS using router in Express.js

I am building a web application using the Express framework. I'm trying to send the username of an account (which is stored in a cookie) to the backend. This is the code in the frontend JS that sends the HTTP Post request:
var httpRequest = new XMLHttpRequest();
httpRequest.open('POST', '/loggedInAutoSubmitForm', true);
httpRequest.setRequestHeader("Content-type","application/application/json");
httpRequest.send(JSON.stringify(content));
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
var json = httpRequest.responseText;
console.log(json);
}
else {
console.log("some error happened");
}
};
content is defined and this is what I get in Chrome's console when I log content:
{"username":"testUser1"}
The content of this request is correct, but I'm not receiving it with the router in index.js. This is the backend code:
var express = require('express');
const router = express.Router();
router.post('/loggedInAutoSubmitForm', function(req, res) {
console.log(req.body);
// find user and render logged in page
});
I haven't implemented the code yet, but the problem is that I'm getting an empty request body. This is what happens in my console when I log req.body:
{}
Also, I get nothing logged in Chrome's console after the request has been sent, so I'm thinking maybe the request didn't end?
I'm fairly new to web development and I'm not sure if this is the correct way to send a Post request from the frontend. If it is, I have no idea what is wrong with this code. I have searched online but it seems that this is the proper way to receive the Post request using router. Is there any way to make it work? Any help is appreciated.

Nodejs server with Express not sending responses to HTTP requests from javascript file, but is receiving the requests and processing them

So I have a node-js server and an apache server on the same machine, and one of the javascript files is sending an HTTP request to the node-js server. The node-js server receives the file, reads the data, puts it in the database, as it should, but it isn't sending back any status codes or data.
Here is the XHTMLRequest send code snippet,
// creates a new http request to be sent to the nodejs server
function createNewUser(username, password, email) {
// The url is the URL of our local nodejs server
var userCreateRequest = new XMLHttpRequest();
userCreateRequest.open( "POST", "http://<machine's IP>:8080/api/users" );
// Create json object for user data
var user = "name="+username+"&password="+password+"&email="+email;
alert(user);
// set content type for http request
userCreateRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Event listern for server response
// userCreateRequest.addEventListener("readystatechange", processRequest, false);
// Call process request whenever state changes
userCreateRequest.onreadystatechange = function() {
alert(this.readyState + ", " + this.status);
if (this.readyState == 4 && this.status == 200) {
var response = this.response;
alert(response.name);
}
}
// Send user data to server
userCreateRequest.send(user);
}
And here is the code for the node-js server (with express)
router.route('/users')
.post(function(req, res) { //create a new user
var user = new User();
user.name = req.body.name;
user.password = req.body.password;
user.email = req.body.email;
user.save(function(err) { //add user object to database
if(err)
res.send(err);
res.status(200).json(user);
});
});
As I said above, the code works fine in terms of putting the body of the request in the database and what-not, but the server is not sending back the 200 OK response (or I'm failing to receive it for some reason). The only times I get an alert from onreadystatechange is when it's state 2, status 0, and state 4, status 0.
Try below code snippet.
user.save(function(err, user) {
if(err)
res.send(err);
res.status(200).json(user);
});
It did end up being a CORS issue. I'm still a little iffy on exactly why, but after configuring the express/CORS package to allow requests from the IP and port of my apache server, it started working.
My understanding is that cross origin implies a different domain, where-as both of my servers are (as I understand it) on different ports on the same domain.
Either way, enabling CORS fixed the issue. Thank you to Jaromanda X for pointing it out and getting me on the right track.

difference between youtube's request and mine

i want to make a script that makes every video's comment section look like the ones that still have the old kind.
for example, videos on this channel:https://www.youtube.com/user/TheMysteryofGF/videos
in Firebug, in the Net tab, i noticed the comment JSON file's URL it is requested from is different.
i tried to run a code on the youtube watch page which would request the file the same way, but it doesnt work, and in firebug it says it was forbidden.
the URL is the same, they are both POST, and i cant figure out what is different. i can even resend the original request in firebug and it works... so anyway, here is a code i tried on a video with "1vptNpkysBQ" video url.
var getJSON = function(url, successHandler, errorHandler) {
var xhr = typeof XMLHttpRequest != 'undefined'
? new XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('post', url, true);
xhr.onreadystatechange = function() {
var status;
var data;
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
if (xhr.readyState == 4) { // `DONE`
status = xhr.status;
if (status == 200) {
data = JSON.parse(xhr.responseText);
successHandler && successHandler(data);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
getJSON('https://www.youtube.com/watch_fragments_ajax?v=1vptNpkysBQ&tr=time&frags=comments&spf=load', function(data) {
alert('Your public IP address is: ' + data);
}, function(status) {
alert('Something went wrong.');
});
You are using Ajax to get data. Ajax has 1 restriction: You can only get data from your own server. When you try to get data from another server/domain, you get a "Access-Control-Allow-Origin" error.
Any time you put http:// (or https://) in the url, you get this error.
You'll have to do it the Youtube way.
That's why they made the javascript API. Here is (the principal of) how it works. You can link javascript files from other servers, with the < script > tag
So if you could find a javascript file that starts with
var my_videos = ['foo', 'bar', 'hello', 'world'];
then you can use var my_videos anywhere in your script. This can be used both for functions and for data. So the server puts this (dynamically generated) script somewhere, on a specific url. You, the client website can use it.
If you want to really understand it, you should try building your own API; you'll learn a lot.
Secondary thing: Use GET.
POST means the client adds data to the server (example: post a comment, upload a file, ...). GET means you send some kind of ID to the server, then the server returns its own data to the client.
So what you are doing here, is pure GET.

GET request in javascript to NodeJS

I'm trying to do a simple conection (request - response) from the javascript code on a web to a server in Node.js.
I have tried to make the request as follows:
var request = new XMLHttpRequest();
request.open('GET', 'http://localhost:4444/', false);
request.send();
if (request.status === 200) {
console.log(request.responseText);
}
Running this code I got an error in FireBug
I have continued searching and I found that this method is only to make GET requests on the same domain. To make cross domain requests we must use other strategies.
I found a jQuery method, and it seems that i'm on the right way:
$.get(
'http://localhost:4444/',
function(data) {
alert("sucess");
//Do anything with "data"
}
);
In this case I get the same response without the error.
It seems it works but the "alert" message is never shown! What happens? What am I doing wrong?
The Node.js server code is:
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.write("Response");
response.end();
}).listen(4444);
So you're running into cross domain issues. You have a few options:
1) since you're using node, use socket.io . It's cross domain compliant.
On the client:
<script src="Full path to were socket IO is held on your server//socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('some_callback', function(data){
// receive data
});
socket.emit('some_other_callback', {'data': value}); //send data
</script>
Server:
var io = require('socket.io').listen(server);
// define interactions with client
io.sockets.on('connection', function(socket){
//send data to client
socket.emit('some_callback', {'data': value});
//recieve client data
socket.on('some_other_callback', function(data){
//do something
});
});
2) Since you just want to use GET you can use JSONP
$.getJSON('url_to_your_domain.com/?callback=?&other_data=something,
function(data){
//do something
}
);
Here we pass your normal GET params as well as callback=?. You will return the following from your server:
require('url');
var r = url.parse(req.url,true);
r.query.callback + '(' + some JSON + ')'
3) If you don't care about all browser compatibility you can use CORS:
You can see a much better example than I would be able to write Here
Cross domain ajax requires special support from your server.
Either CORS: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Which not all browsers support yet. It involves special headers in both the request and response that tell the browser that one domain is allowed to communicate with the other, and for what data.
Or JSONP: http://en.wikipedia.org/wiki/JSONP
WHich will work anywhere, but has some implementation limitations. It involves the server wrapping the response in a javascript function callback that will execute and pass in that data you want.
Either way, the server needs to be setup for each of these approaches.
I think your problem is Same Origin Policy. Your browser must get webpage from node.js instance.
Otherwise, you must use something like CORS. There also good question on SO: Ways to circumvent the same-origin policy.

Javascript Call function serverside

I need to call a Javascript function from the server side in Client side. I looked and didn't find any way how to do it. I looked also over AJAX but can't figure it out. I am using ASP ( clasic) not .net .
I need to call the function in client-side with a variable that comes from the client-side. Please help me!!! Thanks a million !!!
I am using a FlashMovies that is sending a value to a Javascript function through ExternalInterface class. The function in javascript receiving it is gAnswer(result) and in this function i would need to have something like :
Server side:
function saveResult(result)
{code to be saved on the server goes here }
Client side :
function gAnswer (result)
{ saveResult(result) } <- THis is the part i dont know how to do.
The function gAnswer is being called when the flash movie finished by itself.
Would you be able to provide some code on how to ? thanks to each one of you who helped me =)
Call serverside function from client side via Ajax using this here:
function CallServersideFunction() {
url = "CmsAjax.asp";
if (window.XMLHttpRequest) {
http = new XMLHttpRequest()
}
// code for IE
else if (window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP")
}
if (http) {
http.open("GET", url, true)
http.onreadystatechange = handleHttpResponsearticleID;
}
isWorking = true;
http.send(null);
}
function handleHttpResponsearticleID() {
if (http.readyState == 4) {
if (http.responseText.indexOf('invalid') == -1) {
var xmlDocument = http.responseXML;
fno = xmlDocument.getElementsByTagName('id').length;
if (fno > 0) {
alert('Successfully done.')
}
}
}
}
On this page "CmsAjax.asp" you can do your serverside operations.
See http://beaconpush.com, http://pubnub.com, http://pusher.com, et al.
You can't call a function on the server from the client.
The client makes an HTTP request
The server constructs a response (HTML for this example)
The server delivers the response to the client
The client parses the HTML and executes any JS
By stage 4, the program generating the page will have terminated.
If you want something to happen on the server based on a client side script executing, then you need to make a new HTTP request. There are lots of ways you can do this:
Click a link (and include the data in the URI)
Submit a form
Set the src or an iframe
Use XMLHttpRequest (the most common form of Ajax)
Create an <img> and include the data in the src
etc

Categories