Quantcast
Channel: Active questions tagged rest - Stack Overflow
Viewing all articles
Browse latest Browse all 3630

Adding a Front End to a REST API [closed]

$
0
0

I am struggling to figure out how to add a front end to my Rest API. I am Trying to Create a HTML page that dynamically changes based on what url is being visited. I currently get the JSON response from entering "/ListJokes" however i would like to convert this into a HTML page with a title and whatnot similar to "ListJokes.html".

currently i have been receiving the Database in the form of JSON as a response in the browser.

I briefly followed this Tutorial for context: https://www.freecodecamp.org/news/build-consume-and-document-a-rest-api/#how-to-build-a-rest-api-with-node-and-express

My ListJokes.html page:

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>REST Client</title></head><body><div id="joke-container"><h1 style="color:blueviolet; font-size: 60px; text-align: center;">All JOKES!</h1><a href="http://localhost:5000/home"><button type="button">Home Page</button></a><hr><div id="joke-list"></div></div></body></html>

My index.html (homepage):

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>REST Client</title></head><body><div class="container"><h1 style="color:blueviolet; font-size: 60px; text-align: center;">JOKE WEBISTE</h1><hr><div style="margin-bottom: 20px; margin-top: 20px; margin-left: 15px;"><a href="http://localhost:5000/jokes/ListJokes"><button type="button">LIST ALL JOKES!</button></a></div><form id="form" ><div style="margin-bottom: 20px; margin-top: 20px; margin-left: 15px;"><lable for="find joke id">ID: </lable><input type="number" id="find joke id" name="find joke id" style="left: 20px; top: 10px;" placeholder="Enter Joke ID"><button type="submit" style="margin-left: 10px;">Find This Joke!</button></div></form></div><script type="module"></script></body></html>

My Models.js script:

// This is the function definition file for the API. This will recieve data from the control file and will edit the Data Base or The HTML.import Jokes from "./db.js" export const listItems = () => {    try {        console.log(Jokes)        return Jokes                                                         //returns every joke in the Data Base    } catch (err) {                                                              //added error handling        console.log('Error', err)                                                //parses error message    }}

My Controller.js script:

// this file is the head controll file for the API. this will parse the HTTP requests to their corresponding JavaScript function in Models.jsimport bodyparser from "body-parser";                     //Imports Body-Parserimport {    getItem, listItems, editItem, addItem, deleteItem } from "./Models.js"                      //imports functions from Models.jsexport const listJokes = (req, res) => {    try {        const resp = listItems()                                           //parses response into the function        res.status(200)                                                    //sends "It Worked" Message when recieved        res.send(JSON.stringify(resp))    } catch (err) {                                                        //added error handling        res.status(500).send(err)                                          //sends error message to client    }}

My Router.js script:

import express from "express";                            //Imports Express Frameworkimport bodyparser from "body-parser";                     //Imports Body-Parserimport path from "path";import {    listJokes,    getJoke,    editJoke,    addJoke,    deleteJoke,} from "./Controller.js";          //imports function converter from controller.jsconst router = express.Router();                                    //initialises the routerrouter.get("/listJokes", listJokes);                                //monitors endpoint and triggers converterrouter.get("/ListJokes/:id", getJoke);                              //monitors endpoint and triggers converterrouter.put("/editJoke/:id", editJoke);                              //monitors endpoint and triggers converterrouter.post("/addJoke", addJoke);                                   //monitors endpoint and triggers converterrouter.delete("/deleteJoke/:id", deleteJoke)                        //monitors endpoint and triggers converterexport default router;                                              //allows the router to be access remotely

My server.js script:

import router from "./Router.js"import express from 'express'import cors from 'cors'import path from "path";import { fileURLToPath } from 'url';import { dirname } from 'path';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);const app = express()                                  //Starts Appapp.use(cors())                                        //tells app to use corsapp.use(express.json())                                //tells app to use express to handle JSON filesapp.use("/jokes", router)                          //tells app to use the routes from Router.jsapp.listen(5000, () => {                               //Allow the server to scan port 5000 for requests  console.log("Server is running on port 5000.");});app.get("/home", (req, res) => {  res.sendFile(path.join(__dirname, "index.html"));    //Sends index.html file when "/home" is visited});export default app

My db.js File:

var Jokes = [         {            id: 1,            type: "Knock Knock",            setUp1: "Knock Knock",            setUp2: "Whos There?",            setUp3: "Amish",            setUp4: "Amish Who?",            punchline: "Your not a shoe!"        },        {            id: 2,            type: "Knock Knock",            setUp1: "Knock Knock",            setUp2: "Whos There?",            setUp3: "Ben",            setUp4: "Ben Who?",            punchline: "Ben Knocking for 10 Minutes Now Let Me IN!"         },        {            id: 3,            type: "Knock Knock",            setUp1: "Knock Knock",            setUp2: "Whos There?",            setUp3: "Boo",            setUp4: "Boo Who?",            punchline: "Why are you crying, it was only a joke?"        }    ]

I Have removed some functions/parts of the scripts that are not relevent as they follow the rough structure of the ones given. (This explains any random imports or anything like that).


Viewing all articles
Browse latest Browse all 3630

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>