Static HTML with express route

Posted by:

|

On:

|

Example 1

To create an Express route in a file named index.js that handles a HTTP GET request for the path /lastvisit and responds with a plain text containing the timestamp of the previous visit. If a previous visit timestamp exists, it will be sent as plain text in the response. Otherwise, it will respond with “First visit”.

Content of index.js:

const express = require('express');
const app = express();
const port = 3000

let lastVisitTimestamp = null;

app.get('/lastvisit', (req, res) => {
  if (lastVisitTimestamp) {
    res.send(`Last visit: ${lastVisitTimestamp}`);
  } else {
    res.send(`First visit`);
  }
  lastVisitTimestamp = new Date().toISOString();
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

On the Ubuntu terminal, type node index.js, it shows “Server is running on port 3000”. On the PC’s web browser, enter “http://192.168.21.26:3000/lastvisit” where 192.168.21.26 is the IP address of server (Orange Pi with Ubuntu and express JS) returns the following plain message:

Last visit: 2024-05-17T15:45:14.934Z

Example 2

Enter Control+C at Ubuntu terminal to stop the server. Add an additional Express route in “index.js” to manage a HTTP GET request for the route “/colorword”. The response is a valid webpage that includes a level 1 heading displaying the colors red, yellow, green, or blue. The color of the heading text should correspond to the displayed text. Each time the webpage is viewed, it should cycle through the sequence of red, yellow, green, blue, red, and so on.

Content of index.js (code for routes in example 1 are not shown):

const express = require('express');
const app = express();
const port = 3000

const colors = ['red', 'yellow', 'green', 'blue'];
let visitCount = 0;

app.get('/colorword', (req, res) => {
  const color = colors[visitCount % colors.length];
  const html = `
    <!DOCTYPE html>
    <html>
    <head>
      <title>Color Page</title>
      <style>
        h1 {
          color: ${color};
        }
      </style>
    </head>
    <body>
      <h1>${color}</h1>
    </body>
    </html>
  `;

  visitCount++;
  res.send(html);
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

On the Ubuntu terminal, type node index.js, it shows “Server is running on port 3000”. To view the webpage for the first time on your PC’s web browser, enter “http://192.168.21.26:3000/colorword“. The word ‘red’ is shown. By pressing F5, the webpage can be refreshed, and it will display words such as ‘yellow’, ‘green’, ‘blue’, ‘red’, and more.

Example 3

Enter Control+C at Ubuntu terminal to stop the server. Add one more additional Express route in “index.js” to handle a HTTP GET request for the route “/visitlog”. This route should return a webpage that exhibits a collection of timestamps, indicating each visit to the page. Initially, when the page is accessed for the first time, it should display a single timestamp. Subsequent visits should result in the display of an increasing number of timestamps, with each visit adding one more to the list.

Content of index.js (code for routes in example 1 & 2 are not shown):

const express = require('express');
const app = express();
const port = 3000

let visitCount2 = 0;
const timestamps = [];

app.get('/visitlog', (req, res) => {
  visitCount2++;
  const timestamp = new Date().toString();
  timestamps.push(timestamp);

  const listItems = timestamps.map((timestamp) => `<li>${timestamp}</li>`).join('');

  const html = `
    <!DOCTYPE html>
    <html>
    <head>
      <title>Visit Log</title>
    </head>
    <body>
      <h1></h1>
      <ul>
        ${listItems}
      </ul>
    </body>
    </html>
  `;
  res.send(html);
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

On the Ubuntu terminal, type node index.js, it shows “Server is running on port 3000”. On the PC’s web browser, enter “http://192.168.21.26:3000/visitlog” and press F5 three more time, the webpage is shown below:

Sun May 19 2024 21:08:10 GMT+0930 (ACST)
Sun May 19 2024 21:08:12 GMT+0930 (ACST)
Sun May 19 2024 21:08:18 GMT+0930 (ACST)
Sun May 19 2024 21:08:18 GMT+0930 (ACST)

Example 4

Again, enter Control+C at Ubuntu terminal to stop the server. To handle GET requests for both the “welcome.html” and “/main.html” paths, two express routes are implemented. Regardless of whether “welcome.html” or “main.html” is visited, if neither of these pages has been visited before, the user will be redirected to “welcome.html”. On this webpage, a heading saying “Welcome” and a link to continue to the “/main.html” page will be displayed.

If “welcome.html” has been visited before, the user will be automatically redirected to the “/main.html” page. They will see a webpage with a heading saying “Main page” and a message saying “Thanks for visiting us again”.

Content of index.js (code for routes in example 1,2 & 3 are not shown):

const express = require('express');
const app = express();
const port = 3000

let visitedFirstPage = false;

app.use('/welcome.html', (req, res, next) => {
  if (visitedFirstPage) {
    // Redirect to /main.html if the page has been visited before
    res.redirect('/main.html');
  } else {
    // Mark the page as visited and continue to the next middleware
    visitedFirstPage = true;
    next();
  }
});

app.get('/welcome.html', (req, res) => {
  const html = `
    <!DOCTYPE html>
    <html>
    <head>
      <title>Welcome</title>
    </head>
    <body>
      <h1>Welcome</h1>
      <p><a href="/main.html">Continue to main page</a></p>
    </body>
    </html>
  `;

  res.send(html);
});

app.get('/main.html', (req, res) => {
  if (!visitedFirstPage) {
    res.redirect('/welcome.html');
  } else {
    const html = `
      <!DOCTYPE html>
      <html>
      <head>
        <title>Main Page</title>
      </head>
      <body>
        <h1>Main Page</h1>
        <p>Thanks visiting us again</p>
      </body>
      </html>
    `;
  
    res.send(html);
  }
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

On the Ubuntu terminal, type node index.js, it shows “Server is running on port 3000”. On the PC’s web browser, enter “http://192.168.21.26:3000/main.html”, the webpage is automatically redirect to welcome.html as shown below.

However, if it is not the first time visiting these pages, the webpage is automatically redirect to main.html as shown below, regardless of which route you enter on the web browser.

That’s all for today. Let’s study Ajax in the next blog.

Posted by

in