Javascript xmlhttp get request to nodejs server returns nothing

Before starting, I would like to tell you all that I have searched a lot for a solution to this problem myself.

Here is my nodejs node:

var http = require('http'); http.createServer(function (req, res) { console.log("Recived request url " + req.url); var sname = req.url.search("name"); if(sname != -1){ sname = sname + "name".length + 1; var from = sname; while(req.url[sname] != '?' && sname<req.url.length){ sname++; } var name = req.url.substring(from,sname); console.log("Returning parameter of name - " + name); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(name+'\n'); } else{ res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Error - ask about name\n'); } }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/'); 

It listens on port 1337, and if the request URL is correct, it returns some string.

Here is my javascript code requesting nodejs to respond.

 function httpGet(theUrl){ var xmlHttp = null; xmlHttp = new XMLHttpRequest(); xmlHttp.open( "GET", theUrl, true ); xmlHttp.send( null ); return xmlHttp.responseText; } var url = httpGet("http://127.0.0.1:1337/?name=Mateusz"); setTimeout(function(){ document.getElementById("actualnewsspace").innerHTML=url; var xurl = httpGet("http://127.0.0.1:1337/?"+url); },5000) 

the returned xmlHttp.responseText is empty. What for? This is my question.

What my nodejs server has to say in this question

 Recived request url /?name=Mateusz Returning parameter of name - Mateusz Recived request url /? 

If I twist my server, it returns mi the correct value.

+4
source share
1 answer

xmlHttp.responseText not populated when you return it. Ajax Asynchronous .

See Using XMLHttpRequest and bind an event handler to listen when an HTTP response arrives and processes the data.

+3
source

Source: https://habr.com/ru/post/1481722/


All Articles