Search code examples
javascriptnode.jsexpresspug

Ajax call to another Node.js server?


I don't have a specific question, but rather, I need something to be explained. I'm doing an assignment that requires that I use AJAX (WITHOUT JQuery) to display a list once the page loads. However, I'm confused about a part of the instructions.

"...presented with. Once the page loads, an Ajax call should call to a Node.js server to retrieve the top 10 list. Then the list must be presented to the user as numbered list. The items..."

Does this mean I need to create another Node.js server in addition the one I've already created or can this all be done within one server? I'm very confused about this part.

This is my Node.js server.

'use strict';

const express = require('express'),
    request = require('request'),
    app = express();

app.set('view engine', 'pug');
app.set('views', './views');

app.use(express.json());
app.use(express.urlencoded({
    extended: true
}));
app.use(express.static('public'));
app.get('/', function (req, res) {
    res.render('index');
});

app.listen(3000, function () {
    console.log('Listening on http://localhost:3000');
});

This is my PUG template.

doctype
html
    head
        meta(charset="UTF-8")
        meta(name="viewport", content="width=device-width, initial-scale=1")
        block title
            title This is the title!
        link(rel='stylesheet', href='/css/style.css', type='text/css')
    body
        h1 This is a header!

        div#banner

        p#demo This is a description!

        script(src='/js/mrvl_ajax.js')

This is my AJAX call function.

'use strict';

window.addEventListener("load", function(event) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        document.getElementById("demo").innerHTML = this.responseText;
    };
    xhttp.open("GET", "**Server Location?**", true);
    xhttp.send();
});

Solution

  • You can create another endpoint on your Node.js server.

    app.get('/data', function (req, res) {
        res.json({"list": ["item1", "item2"]});
    });
    

    then call that endpoint from the client with ajax

    xhttp.open("GET", "/data", true);
    

    the data returned will be the JSON data {"list":["item1", "item2"]}, which you can then use javascript to order it how you need to.

    also, inside your onreadystatechange function you will want this if statement to make sure the call completed successfully before you grab the responseText from the response

    xhttp.onreadystatechange = function() {
        if (xhttp.readyState === 4 && xhttp.status === 200) {
          document.getElementById("demo").innerHTML = xhttp.responseText;
        }
    }