0

Okay, very new to both javaScript and Node.js.

Basically what I am trying to do is to use the asynch module (a node.js module) to make a number of asynchronous calls to a number of different 'websites'.

For example, just send a GET request to 5 websites, and print their response.

The issue is that I am trying to use the XMLHttpRequest(); javascript object, but it doesn't seem to work in Node.js, saying it is undefined. I believe this is because that object needs to be used within a browser. Is this true?

At anyrate, how can I send a get request using Node.js? Without have embedded javascript in HTML or anything like that. Strictly Node.JS. This should be really simple shouldn't it?

Here is a pretty basic example of what I mean (taken from a book somewhere):

function myFunction(theUrl) {

    var xmlHttp = null;

    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false );
    xmlHttp.send();
    console.log(xmlHttp.responseXml);
    console.log("Finished!");
    return xmlHttp.responseText;

}

EDIT:

Okay I have succesfully sent a "GET" request (I believe).

I am printing the output to a file (just for testing). Except, I get a buttload of XML (maybe JSON) back, but there is no "200 OK" message anywhere in it.

If I send a "HEAD" request, I get nothing back.

Two questions: Why aren't I getting that 200 OK message back? And what is all the XML I get back? Also, why doesn't the "HEAD" request return anything? Is Node.JS stripping that out?

I want to seperate the message response (hopefully "200 OK") and all the other headers. How can I do this if I don't get headers??

1

1 Answer 1

1

I believe this is because that object needs to be used within a browser. Is this true?

Not exactly.

  • XMLHttpRequest is not part of core JavaScript, it is a W3C specification
  • Browsers supply an XMLHttpRequest object, so you don't have to do anything special to use it from a browser.
  • A third party XMLHttpRequest module is available for Node.js via NPM. (I've used it for writing command line tests for a JS library that normally runs in the browser.)

You just need to install the module and require it (as per the instructions in the documentation).

Sign up to request clarification or add additional context in comments.

2 Comments

Wow thank you so much. I've been all over tutorials and google and stack exchange for hours trying to figure this out...so simple lol.
Okay so I figured out sending a 'GET' request.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.