Home > Net >  Send data from server to client trough fetch in vanilla javascript
Send data from server to client trough fetch in vanilla javascript

Time:11-07

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:

<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

CodePudding user response:

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);
});
  • Related