Basic Ajax send / receive using node.js

So, I'm trying to create a very simple node.js server that, taking a query on a string, randomly selects one from the array and returns the selected string. Unfortunately, I have a few problems.

Here's the front end:

function newGame() { guessCnt=0; guess=""; server(); displayHash(); displayGuessStr(); displayGuessCnt(); } function server() { xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET","server.js", true); xmlhttp.send(); string=xmlhttp.responseText; } 

This should send a server.js request:

 var http = require('http'); var choices=["hello world", "goodbye world"]; console.log("server initialized"); http.createServer(function(request, response) { console.log("request recieved"); var string = choices[Math.floor(Math.random()*choices.length)]; console.log("string '" + string + "' chosen"); response.on(string); console.log("string sent"); }).listen(8001); 

So it’s clear that several errors occur here:

  • It seems to me that I am β€œconnecting” these two files incorrectly both in the xmlhttp.open method and when using response.on to send a string back to the interface.

  • I am a little confused by the way I call this page on localhost. The front end is called index.html and the sever message is 8001. What address should I go to localhost in order to access the html start page after initializing server.js? Should I change it to .listen(index.html) or something like that?

  • Are there any other obvious issues with the way I implement this (using .responsetext , etc.)

(sorry for the long multi-task post, but various tutorials and the source of node.js all assume that the user already understands these things.)

+45
javascript ajax
May 15 '11 at 23:31
source share
4 answers
  • Your request should be on the server, and not on the server.js file that creates it. Thus, the request should look something like this: xmlhttp.open("GET","http://localhost:8001/", true); Also, you are trying to serve front-end (index.html) and serve AJAX requests in the same URI. To do this, you will need to enter the logic on your server.js, which will distinguish between your AJAX requests and the usual request for access to http. To do this, you need to either enter the GET / POST data (i.e. call http://localhost:8001/?getstring=true ), or use a different path for your AJAX requests (i.e. call http://localhost:8001/getstring ). At the end of the server, you will need to examine the request object to determine what to write in response. For the latter, you need to use the url module to parse the request.

  • You call listen() correctly, but misspelled the answer. First of all, if you want to serve index.html while navigating at http: // localhost: 8001 / , you need to write the contents of the file in response using response.write() or response.end() . First, you need to enable fs=require('fs') to gain access to the file system. Then you need to actually file the file.

  • XMLHttpRequest requires a callback function if you use it asynchronously (third parameter = true, how you did it) and want to do something with the answer. Now you have a string will be undefined (or possibly null ), because that string will be executed until the AJAX request completes (i.e. ResponseText is still empty). If you use it synchronously (third parameter = false), you can write inline code as you did. This is not recommended as it blocks the browser during the request. An asynchronous operation is typically used with the onreadystatechange function, which can process the response after it is completed. You need to learn the basics of XMLHttpRequest. Start here .

Here is a simple implementation that includes all of the above:

server.js:

 var http = require('http'), fs = require('fs'), url = require('url'), choices = ["hello world", "goodbye world"]; http.createServer(function(request, response){ var path = url.parse(request.url).pathname; if(path=="/getstring"){ console.log("request recieved"); var string = choices[Math.floor(Math.random()*choices.length)]; console.log("string '" + string + "' chosen"); response.writeHead(200, {"Content-Type": "text/plain"}); response.end(string); console.log("string sent"); }else{ fs.readFile('./index.html', function(err, file) { if(err) { // write an error response or nothing here return; } response.writeHead(200, { 'Content-Type': 'text/html' }); response.end(file, "utf-8"); }); } }).listen(8001); console.log("server initialized"); 

frontend (part of index.html):

 function newGame() { guessCnt=0; guess=""; server(); displayHash(); displayGuessStr(); displayGuessCnt(); } function server() { xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET","http://localhost:8001/getstring", true); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ string=xmlhttp.responseText; } } xmlhttp.send(); } 

You will need to be comfortable with AJAX. Use the mozilla Learning Center to learn about XMLHttpRequest. After using the main XHR object, you will most likely want to use a good AJAX library instead of manually writing AJAX requests to a cross browser (for example, in IE you need to use ActiveXObject instead of XHR). AJAX in jQuery is excellent, but if you don't need all the rest of jQuery , find a good AJAX library here: http://microjs.com/ . You will also need to come up with the node.js docs found here . Search http://google.com for some good node.js servers and static file servers. http://nodetuts.com is a good place to start.

UPDATE: I changed response.sendHeader() to a new response.writeHead() in the code above !!!

+50
May 16 '11 at 1:49
source share

Express makes this material truly intuitive. The syntax is as follows:

 var app = require('express').createServer(); app.get("/string", function(req, res) { var strings = ["rad", "bla", "ska"] var n = Math.floor(Math.random() * strings.length) res.send(strings[n]) }) app.listen(8001) 

http://expressjs.com/guide.html

If you are using jQuery on the client side, you can do something like this:

 $.get("/string", function(string) { alert(string) }) 
+25
Dec 07 '11 at 3:32
source share

I encountered the following error with code (nodejs 0.10.13) provided by ampersand:

origin is not allowed with access-control-allow-origin

Problem resolved with change

 response.writeHead(200, {"Content-Type": "text/plain"}); 

to

 response.writeHead(200, { 'Content-Type': 'text/html', 'Access-Control-Allow-Origin' : '*'}); 
+5
Jul 16 '13 at 13:49 on
source share

Here is a fully functional example of what you are trying to accomplish. I created an example inside hyperdev and not jsFiddle so you can see the server and client code.

View code: https://hyperdev.com/#!/project/destiny-authorization

View working app: https://destiny-authorization.hyperdev.space/

This code creates a handler for the receive request, which returns a random string:

 app.get("/string", function(req, res) { var strings = ["string1", "string2", "string3"] var n = Math.floor(Math.random() * strings.length) res.send(strings[n]) }); 

This jQuery code then executes an ajax request and receives a random string from the server.

 $.get("/string", function(string) { $('#txtString').val(string); }); 

Please note that this example is based on the code from Jamund Ferguson's answer, so if you find this useful, be sure to upgrade it. I just thought this example would help you see how everything fits together.

0
Nov 18 '16 at 18:05
source share



All Articles