Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Send data from server to client with vanilla nodejs and javascript

good afternoon, I have tried to make a mini app where when you click the button a fetch is made to the backend and it returns a little information.

But my problem is that the call goes well, since it returns a 200 as status, but the information does not arrive.

This is the client code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<html lang="en">
 <head>
   <meta charset="UTF-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <title>prueba</title>
</head>

  <body>
   <button type="submit" id="upload">received information</button>
   <script>
     const submitButton = document.getElementById("upload");

     submitButton.addEventListener("click", (event) => {
       event.preventDefault();

       fetch("http://localhost:8000/", {
         method: "GET",
         }).then((res) => {
         console.log("Request complete! response:", res);
        });
      });
   </script>
  </body> 
 </html>

This is the server code:

import http from "node:http";

  http.createServer((req, res) => {
   const headers = {
  "Access-Control-Allow-Origin": "*",
  "Content-Type": "application/json",
};

if (req.url === "/" && req.method === "GET") {
  res.writeHead(200, headers);
  res.write(JSON.stringify({ message: "Hello" }));
  res.end();
  return;
}
}).listen(8000, () => {
console.log("The server is active on the port 8000");});

This is the data that the server responds to me:

The image of the data that the server responds to me

>Solution :

The res to which the fetch statement resolves is the response object, not the text of the response. To get the text, use the text() function of the response object:

fetch("http://localhost:8000/", {method: "GET"})
.then(res => res.text())
.then(text => {
  console.log("Request complete! response:", text);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading