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." }