skip to Main Content

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


  1. try this pls:

    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());
    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);
    });
    
    
    app.listen(9000, "127.0.0.1", () => {
      console.log("listening on port 9000");
    });
    Login or Signup to reply.
  2. 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 using fetch and $.ajax but in express you are only listening for / and player routes.

    to fix this issue you have to remove app.get("/test", function (req, res) {...}) function from if (pathname == "/player") block and put it outside of server callback function like below.

    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);
    });
    
    const server = http.createServer((req, res) => {
      // Your existing code here
    });
    

    this will create a route that listen for /test in your express app and sends a json object. now you can call this route using fetch in your HTML script like below

    fetch('http://localhost:9000/test')
      .then(res => res.json())
      .then(data => {
        console.log("Hi? : ", data); // { name: "John", age: 30 }
      })
      .catch(console.error);
    

    this should now work and the data should logged out to the console.

    Login or Signup to reply.
  3. 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

    <html>
    <script src='https://code.jquery.com/jquery-3.6.4.min.js'></script>
    <script>
      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: "https://xise6v-9000.csb.app/test",
        complete: function(data) {
         console.log(data?.responseText);
        }
      });
    </script>
    </html>
    

    update your app.js file to resemble the code below. I have included comments to provide more context and understanding:

    const express = require("express");
    const app = express();
    
    app.use(
      express.urlencoded({
        extended: true
      })
    );
    
    // serve the html file under the public folder
    app.use(express.static("public"));
    app.use(express.json());
    
    
    // correct way to declare the API
    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);
    });
    
    // use app listen instead
    app.listen(9000, "127.0.0.1", () => {
      console.log("listening on port 9000");
    });
    

    You can preview the result by following this link.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search