Share
Explore

Node API Exercise: The JOKES API

info



New skills in this lab: Building the FULL Stack Web Application

We have started to look at how JavaScript is used in the browser.
Now we will look at NODE.js
Download from
megaphone

Node.js is a platform on which we run programs in the JavaScript language.

In addition to writing programs (to be Controller), we also need a back end data persistence layer called “The Model”. We will use MONGO database to do this.
Now download the Mongo Database install
This will provide the data storage for our Node.js Programs:
Go to https://www.mongodb.com/try/download/community
Download the latest Community Edition.

Tools Needed to make this happen:

We already have Visual Studio Code.
Now let’s get our back end “processing engine” which is Node.js
Getting setup:
Step 1: Learn how to program Node.js in Visual Studio Code.
Step 2: Use VSC to make a simple web page which connects with Node.js

This exercise will cover setting up a basic API, handling JSON data, and making HTTP requests from the client side.
It also provides a clear path for future enhancements, such as integrating with a MongoDB database.
Here's a detailed lab exercise plan for setting up the Jokes API:

Lab Exercise: Setting Up the Jokes API

Objective:

Create a simple Node.js server with a hard-coded list of jokes.
Develop a client-side application that fetches and displays a new joke each time it is run.
Discuss how this can be extended to fetch jokes from a MongoDB database in the future.

Part 1: Setting Up the Node.js Server

1. Initialize the Project

Create a new directory for the project and navigate into it:
mkdir jokes-api
cd jokes-api
Initialize a new Node.js project:
bash
Copy code
npm init -y

Install the required dependencies:
bash
Copy code
npm install express

2. Create the Server

Create a file named server.js:

// server.js
const express = require('express');
const app = express();
const port = 3000;

const jokes = [
{ id: 1, joke: "Why don't scientists trust atoms? Because they make up everything!" },
{ id: 2, joke: "Why did the scarecrow win an award? Because he was outstanding in his field!" },
{ id: 3, joke: "Why don't programmers like nature? It has too many bugs." },
{ id: 4, joke: "Why do cows have hooves instead of feet? Because they lactose." },
{ id: 5, joke: "Why was the math book sad? Because it had too many problems." }
];

app.get('/joke', (req, res) => {
const randomIndex = Math.floor(Math.random() * jokes.length);
const randomJoke = jokes[randomIndex];
res.json(randomJoke);
});

app.listen(port, () => {
console.log(`Jokes API server running at http://localhost:${port}`);
});

Run the server:
bash
Copy code
nodemon server.js

Test the API endpoint in a browser or using a tool like Postman by visiting:
bash
Copy code
http://localhost:3000/joke

Explanation:

Explain the basics of setting up an Express server.
Discuss how the server selects and returns a random joke from the hard-coded list.
Mention that this server could be extended to fetch jokes from a database like MongoDB in the future.

Part 2: Creating the Client-Side Application

1. Create the HTML File

Create a file named index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Jokes API Client</title>
</head>
<body>
<h1>Joke of the Moment</h1>
<p id="joke"></p>
<button onclick="fetchJoke()">Get a New Joke</button>

<script>
function fetchJoke() {
fetch('http://localhost:3000/joke')
.then(response => response.json())
.then(data => {
document.getElementById('joke').textContent = data.joke;
})
.catch(error => console.error('Error:', error));
}

// Fetch a joke when the page loads
fetchJoke();
</script>
</body>
</html>

Explanation:

Describe how the Fetch API is used to make a GET request to the server.
How is the response is processed and displayed on the web page?
Discuss the role of the fetchJoke function and how it updates the DOM.

Part 3: Extending the Project

Future Enhancements:

Using MongoDB:
Explain how MongoDB can be integrated to store and retrieve jokes.
Mention tools like Mongoose for schema management and data validation.
Client-Side Enhancements:
Adding a form to submit new jokes.
Implementing error handling and user feedback.

Lab Exercises:

Exercise 1: Set up the Node.js server and test the /joke endpoint.
Exercise 2: Create the HTML file and ensure it can fetch and display a joke.
Exercise 3: Modify the server to add more jokes or change the format of the jokes.
Exercise 4: Extend the client-side application to handle errors and display appropriate messages.

Conclusion:

Recap the steps taken to create the Jokes API.
Highlight the key learning points, such as setting up a server, handling JSON data, and making HTTP requests.
Think about how you can further enhance the project with additional features.

This lab exercise provides a hands-on approach to understanding APIs, making it practical and engaging for students.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.