Blog post loading on web page with Ajax & Express

Posted by:

|

On:

|

Create a static page called blog.html in the public folder.

<!DOCTYPE html>
<html>
<head>
  <title>Blog</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <h1>Blog</h1>

  <div id="blog-container"></div>
  <button id="load-more-btn">Load More</button>

  <script>
    $(document).ready(function() {
      const blogContainer = $('#blog-container');
      const loadMoreBtn = $('#load-more-btn');
      let firstIndex = 0;

      const loadBlogPosts = (num) => {
        $.ajax({
          url: `/posts.json?num=${num}&first=${firstIndex}`,
          type: 'GET',
          dataType: 'json',
          success: function(data) {
            data.forEach(post => {
              const postDiv = $('<div>').addClass('post');
              const timestampP = $('<p>').addClass('timestamp').text(post.timestamp).css('color', 'grey');
              const authorP = $('<p>').addClass('author').html(`<a href="${post.website}">${post.author}</a>`);
              const contentP = $('<p>').text(post.content);

              postDiv.append(timestampP, authorP, contentP);
              blogContainer.append(postDiv);
            });

            firstIndex += num;
          },
          error: function(jqXHR, textStatus, errorThrown) {
            console.error('Error:', textStatus, errorThrown);
          }
        });
      };

      loadBlogPosts(4); // Initial load

      loadMoreBtn.on('click', function() {
        loadBlogPosts(4); // Load 4 more blog posts on each button click
      });
    });
  </script>
</body>
</html>

Content of the server7.js

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

// Array of blog posts
const blogPosts = [
  {
    timestamp: '2024-01-01',
    author: 'John Doe',
    content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam non augue et arcu cursus fermentum. Sed tincidunt justo vitae volutpat sodales.',
    website: 'https://example.com/john'
  },
  {
    timestamp: '2024-01-05',
    author: 'Jane Smith',
    content: 'Praesent consectetur neque et tincidunt viverra. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.',
    website: 'https://example.com/jane'
  },
  // Add more blog posts here...
];

// Route handler for /posts.json
app.get('/posts.json', (req, res) => {
  let num = parseInt(req.query.num); // Get the value of "num" from the query string
  let first = parseInt(req.query.first); // Get the value of "first" from the query string

  // Validate and adjust the values of "num" and "first"
  if (isNaN(num) || num < 1) {
    num = blogPosts.length; // Send all blog posts if "num" is not a valid integer or less than 1
  }

  if (isNaN(first) || first < 0) {
    first = 0; // Start from the first blog post if "first" is not a valid integer or less than 0
  }

  // Get the subset of blog posts based on "num" and "first"
  const subsetPosts = blogPosts.slice(first, first + num);

  res.json(subsetPosts);
});

app.use(express.static('public'));

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

The appropriate file structure should resemble the following:

- public
  - blog.html
  - js
    - jquery-3.7.1.min.js
- server7.js

Run the Express application by executing the following command in the Ubuntu terminal:

node server7.js

Make sure both Orange Pi and PC have the same subnet and connect to the same router or network switch. On the PC’s web browser, enter the following URL where 192.168.21.26 is the IP address of the Orange Pi.

http://192.168.21.26:3000/blog.html

Posted by

in