I have a made a JSON object using Node JS functions, and now I want to send this JSON object to the HTMl side so that I can make a table with the data. However, it’s not being sent over, and since I am quite new to Node JS, I’m unsure how I can send this JSON object over.
When I use Express to send the object and use fetch in the script of my HTML file, the console.log in Chrome developer tools (under the network tab) shows as pending, and data from the console.log does not show. I checked on Postman as well, and the request to the localhost URL just shows it grinding as "Sending Request".
const http = require("http");
const fs = require("fs");
const url = require("url");
const express = require("express");
const app = express();
app.use(
express.urlencoded({
extended: true,
})
);
app.use(express.json());
const server = http.createServer((req, res) => {
const { query, pathname } = url.parse(req.url, true);
if (pathname == "/") {
res.writeHead(200, { "Content-type": "text/html" });
const outMap = Array.from(teams)
.map((el) => homepageTeamLister(teamsListHTML, el))
.join("");
res.end(outMap);
} else if (pathname == "/player") {
//res.writeHead(200, { "Content-type": "text/html" });
app.get("/test", function (req, res) {
res.setHeader(
"Access-Control-Allow-Origin",
"http://localhost:9000/test"
);
res.setHeader("Access-Control-Allow-Methods", "GET");
const myObj = { name: "John", age: 30 };
res.send(myObj);
});
}
});
server.listen(9000, "127.0.0.1", () => {
console.log("listening on port 9000");
});
And my HTML Script code:
console.log("Entered Script");
fetch('/test')
.then(res => res.json())
.then(data => {
console.log("Hi? : " , data); // { name: "John", age: 30 }
})
.catch(console.error);
$.ajax({
url: 'http://localhost:9000/test',
complete: function(data) {
console.log(data);
}
I have tried both the fetch function, and used AJAX, but both attempts did not work.
3
Answers
try this pls:
it seems you define a route
/test
but you are not actually called the route in your HTML script.the problem here is you are calling
/test
usingfetch
and$.ajax
but in express you are only listening for/
andplayer
routes.to fix this issue you have to remove
app.get("/test", function (req, res) {...})
function fromif (pathname == "/player")
block and put it outside ofserver
callback function like below.this will create a route that listen for
/test
in yourexpress
app and sends a json object. now you can call this route usingfetch
in your HTML script like belowthis should now work and the data should logged out to the console.
It appears that your code for Express.js and HTML was not set up correctly.
You can preview the final code here
place the HTML code below to
public/index.html
update your app.js file to resemble the code below. I have included comments to provide more context and understanding:
You can preview the result by following this link.