Question: To create a Node.js server that serves Klingon jokes and a front - end HTML page with a button to fetch and display a new
To create a Node.js server that serves Klingon jokes and a frontend HTML page with a button to fetch and display a new joke, follow these steps:
Set up the project: Make sure you have Node.js and npm installed.
Create the project directory and initialize:
bash
mkdir klingonjokesapp
cd klingonjokesapp
npm init y
npm install g express bodyparser
Create the main application file appjs:
javascript
const express requireexpress;
const app express;
const port ;
List of Klingon jokes
const jokes
"A Klingon, a Ferengi, and a Betazoid woman were sitting around in Quark's bar...",
Q: How many Klingons does it take to change a light bulb? A: None. Klingons aren't afraid of the dark.",
"Klingons do not make software bugs. Their software is perfect from the first compile.",
"Klingon programming does not tolerate error messages."
;
Middleware to serve static files HTML CSS JS
app.useexpressstaticpublic;
API endpoint to get a random joke
app.getjokereq res
const randomIndex Math.floorMathrandom jokes.length;
const joke jokesrandomIndex;
res.json joke ;
;
app.listenport
console.logApp listening at http:localhost:$port;
;
Create the public directory and HTML file:
bash
mkdir public
cd public
Create the HTML file indexhtml:
html
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
