0

Using a node , I have a client-server model , where the client would connect to "localhost" and express will provide a response based on logic. I understand how to send the json object through the response , but I don't know how to access this json object in my client-side script. Newbie question any ideas?

server:

app.get("/", function(request,response){
 response.json({ username: 'example' })
 
 })
RonRon Scores
  • 163
  • 2
  • 11
  • Your client javascript can make a GET request to the route "/". You can use many techniques to make this request, such as using the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API, XMLHttpRequest, jQuery's $.ajax, angular's HttpClient module, axios, etc... If you're using vanilla JS on the client-side, then [fetch()](https://stackoverflow.com/a/59916857/5648954) is probably the easiest option. – Nick Parsons Dec 08 '20 at 02:55
  • Does the fetch , act as a second get request? Or does it just provide the data stored from the initial get request – RonRon Scores Dec 08 '20 at 03:02
  • It will act as a second GET request. When you enter localhost (ie: a URL) into your browser, your browser will make a GET request for you, your server can then respond with the page contents such as the HTML of the page you just request, CSS, JS, etc. Then, at a later time, your JS code can make a second (or third or fourth or etc...) request to your server for a specific route, which will usually respond with JSON (like in your example) – Nick Parsons Dec 08 '20 at 03:06

1 Answers1

0

If you use Vanilla JS, you have a few options such as Fetch API, XMLHttpRequest, ajax.

1. Fetch API :

fetch('http://localhost:3000/')
    .then(response => console.log(response));

2. XMLHttpRequest :

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       console.log(xhttp.responseText);
    }
};
xhttp.open("GET", "http://localhost:3000/", true);
xhttp.send();

3. Ajax :

$.get("http://localhost:3000/", function(data, status){
    console.log(data);
  });

You can replace the "http://localhost:3000/" with your URL.

Harshana
  • 5,151
  • 1
  • 17
  • 27