-1

I am new to web development and cannot figure out how to send data from the Node server to the client while also serving an HTML page. I know that res.send() sends the data but I cannot use that without also changing the client display. Here is some code of what I'm trying to do (but does not work)

Server:

app.get('/home', function (req, res) {
    res.send("String with info I want in HTML");
    res.sendFile(__dirname + '/home.html');
});

Client:

<script>
        var xhttp = new XMLHttpRequest();
        alert(xhttp.responseText); //Using alert to check if I received the info I wanted
</script>
Kevin
  • 1
  • if you use handlebars View Engine you can do this `res.render('home', {myText:'your string here'})` while you add a palceholder in the template {{myText}} – Ahmed Abdelaal May 14 '18 at 01:28
  • To start with, you need to send a proper Ajax request from the client. The code you show is just a small piece of an ajax request. There are thousands of places on the web where you can read how to make an ajax call from browser Javascript. Then, you just create a route in your server for the URL that your ajax call is requesting and send ONE response (not the two you show). That response will go back to the ajax caller and they will receive it in their Javascript and can decide what to do with it. That's it. No client display change. Ajax calls don't change the display on their own. – jfriend00 May 14 '18 at 04:06

2 Answers2

0

I know that res.send() sends the data but I cannot use that without also changing the client display.

You can. You just have to have the client ask for the data in the right way.

If the client side code is asking for a URL to be displayed as a new page then you will change the display. So don't do that. Use XMLHttpRequest.

var xhttp = new XMLHttpRequest();
alert(xhttp.responseText); //Using alert to check if I received the info I wanted

You need to:

  1. Create the XHR object
  2. Ask for a URL
  3. Send the request
  4. Wait for the response
  5. Look at the response

You've skipped over steps 2, 3 and 4!

var xhttp = new XMLHttpRequest();
xhttp.open("GET", "/home");
xhttp.addEventListener("load", function () { alert(this.responseText); });
xhttp.send();
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

res.render() function does the job!

res.render("your html page" , { variable : "String with info you want to send." })