2

I have an express server running that sends an html file from the public folder of my project. It is from a client script linked from this html file that I am trying to request and send data to the server. I have looked just about everywhere and have had no luck finding a way to do this. I thought that it could be done just using express but I cannot seem to figure it out. I feel like I must be missing or misunderstanding something obvious. How can I do this?

|--index.js
|--template.json
|--public
|  |--index.html
|  |--client.js

1: Here is my file structure. I am trying to have client.js send a request to index.js which then will respond with some json.


Any solutions or even just pointers are appreciated.

kevinuulong
  • 530
  • 1
  • 4
  • 17

1 Answers1

3

Here's a simple setup:

1) Express serves index.html from public/ folder which executes client.js

2) We have an Express route which reads the template.json file and loads it in a route at /json/

3) The client.js does an Ajax request via fetch(), hits the /json/ route, which serves the JSON content to the browser script

index.js

const express = require("express");
const app = express();
const data = require("./template.json");

app.use( express.static( __dirname + '/public' ) );

app.get("/json", (req,res)=>{
    // Send a JSON response with the data from template.json
    res.json( data );
})

app.listen( 8080 );

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Express</title>
</head>
<body>
    <h1>Express</h1>
    <script src="client.js"></script>
</body>
</html>

client.js

// Make an HTTP request to the /json/ route of our express server:
fetch("/json")
// Get the request body and convert to JSON:
.then((res)=> res.json())
// Here we have the request body as a JSON object ready to be used:
.then((data)=>{

    console.log( data );

})
.catch(console.error);

template.json

{"firstname":"john","lastname":"doe"}

References:

Kostas Minaidis
  • 4,681
  • 3
  • 17
  • 25
  • If I were to then create a folder with multiple json files in it would I have to require each file individually or could I require an entire folder? – kevinuulong Oct 12 '19 at 00:13
  • Yes, you must require each file individually, through some kind of loop. @kevinuulong Maybe these will help: https://stackoverflow.com/questions/10049557/reading-all-files-in-a-directory-store-them-in-objects-and-send-the-object – Kostas Minaidis Oct 12 '19 at 15:32