Reputation: 550
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.
Upvotes: 2
Views: 5080
Reputation: 5412
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:
Upvotes: 3