1.3 - GET requests

  • Posted on: 25 July 2018
  • By: Ryoma Ohira
Tools: 
NodeJS
Express
Difficulty: 
Intermediate
Prerequisites: 
1.2 - Setting up a basic Express project

Getting Started

Let's start with a new project using the following file structure

  • root/
    • server.js
    • www/
      • index.html

With the following code for the files

server.js

// server.js
var express = require('express');
var http = require('http');
var app = express();

var host = '127.0.0.1';
var port = 3000;

var http = require('http').Server(app);
app.use(express.static(__dirname + '/www'));

var server = http.listen(port,host,function(){
    console.log('Server listening on ' + host + ':' + port);
});

app.get('/', function(request, response){
    response.sendFile(__dirname + '/index.html');
});

index.html

As before, this is a basic HTML page but we've included the jQuery library that is made available through the Google api CDN. Inside our <head></head> tags, we've also included our own jQuery script that will run once the webpage has loaded. The reason why we have the $(document).ready(); function is that HTML will procedurally run content as it loads. We can use this function if we want to run some code once the whole page has been loaded and is ready to go. With console.log(), anything within the brackets is printed out on the browser's console and we can use it for debugging purposes. 

<!doctype>
<html>
    <head>
        <title>Workshop 1.3</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                console.log("page is ready");
            });
        </script>
    </head>
    <body>
        <h1>Index.html</h1>
    </body>
</html>

Create a New Route

Back in server.js create a new route that uses '/getData' and returns some HTML as a response. 


app.get('/getData', function(request, response){
    response.send("<h1>This is the response</h1>");
});

As we are sending a string as data, we use send instead of sendFile. 

Next in our index.html add a bit of code after our console.log();  so that we can access this new route and retrieve the response.

$.get('/getData', function(data){
    alert('Data loaded: ' + data);
});

Now by running the server using node server.js in terminal, we can access the webserver on http://localhost:3000 to see if our GET request is working. You should see your index.html with an alert saying "Data loaded: <h1>This is the response</h1>". Congratulations, your GET request works but let's make it a little more useful. 

Dynamic Content

JavaScript and jQuery in particular is a great way of creating webpages with dynamic content. By manipulating Document Object Model (DOM) objects in our HTML, we can add, modify or remove content without having to refresh the page. Let's add this text to our webpage by creating a div underneat our <h1></h1> tags in our index.html.

<div id="content"></div>

<div></div> tag creates a division section in our HTML document. Think of it as a content section that you can style and fill with what ever content you like. Applying an id and value to this tag lets us uniquely identify which DOM object we want to manipulate through JavaScript. 

We can then update our <script>...</script> content to access this DOM object and insert our data into it. The script should look something like the code below:

$(document).ready(function(){
    console.log("page is ready");

    $.get('/getData', function(data){
        $('#content').html(data);
    });
});

To explain, what we are doing is using jQuery to select the DOM object with id='content' and then modifying the html parameter to contain the response from our GET request. If we run our server and refresh our page, we can now see that the content is styled and displayed as part of the HTML rather than as an alert. This is useful when it comes to requesting and presenting data on our webpage through a GET request. 

Closing Notes

As mentioned earlier, we can add JavaScript into our HTML pages by writing the code within <script>...</script> tags. However, sometimes this gets unwieldly if we end up with a lot of code. What we can do is decouple our code a little more so that our HTML page only contains our content and create a new JS file that will have our code in it. To do so, create a new script.js file inside our www folder. Copy and paste all the code within our <script>...</script> tags into this new file. Modify our script tag so that it point to a new source called script.js. Your new code should look something like one one below:

<head>
    <title>Workshop 1.3</title>
    <script
        src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="script.js"></script>
</head>

This will allow you to run the code but keep your files and code neat and organised. Refer to to appendix for the content for each file

Category Terms: 
Tutorial Weight: 
13

Comments

Every user have requests to get more information on law assignment writing innovative topics.. That all much useful and helpful to all the essay writers and assignment review writers of this blog.

It's superior, however , check out material at the street address. logo maker

These websites are really needed, you can learn a lot. Relationship Rewrite Method

This post is really magnificent. I really like this post. It is one of the best posts that I ve read in a long time. Thanks a lot for this really good post. I really appreciate it! Manifest Magic

HyperText Markup Language, the coding language used to create hypertext documents for the World Wide Web. Do my assignment for me

I like your site. You have a comprehensive knowledge about index html. Your opinions about jQuery setup were valued. The images you shared were really cooperative. Your way of leadership was simply nice. Thanks for placement blog. I am a regular reader of you’re... buy assignment writing