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

how can i print a response from server using express and fetch?

i am getting object response when trying to use the response from express,this is the HTML and client js i am using

    <html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  </head>
  <body>
    <form method="post">
      <input id="names" name="names" type="text" />
    </form>
    <button id="send">send</button>
    <p id="text"></p>
    <script>
      document.getElementById("send").addEventListener("click", () => {
        
        let datos = {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            names: document.getElementById("names").value,
          }),
        };

        fetch("/myaction", datos)
          .then(function (response) {
            document.getElementById("text").innerHTML = response;
          })
          .catch(() => {
            document.getElementById("text").innerHTML = "Error";
          });
      });
    </script>
  </body>
</html>

i am trying to use the response of the server.js in the "text" element, the server is

var express = require('express');
var bodyParser = require('body-parser');
var app     = express();
app.use(express.json()) 
//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true })); 

//app.use(express.bodyParser());
app.get('/', function(req, res) {
  res.sendFile(__dirname + "/index.html");
});

app.post('/myaction', function(req, res) {
  res.send(req.body.names);
});

app.listen(8088, function() {
  console.log('Server running');
});

when fetch request myaction express return the name query but i cant use it on the fetch then because it print "[object Response]" instead the name form value, what can i do ?

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

>Solution :

The global fetch function returns a Promise that resolves to a Response object. This object contains all the information about the response, like headers, status, body, etc. To get the body of the response you’ll need to decode the response first.

In your case you need to read the body as a string so we’ll use response.text(). This is a method on the Response object. It also returns a promise which resolves to a string.

fetch("/myaction", datos)
  .then(function (response) {
    return response.text();
  })
  .then(function (text) {
    document.getElementById("text").textContent = text;
  })
  .catch(() => {
    document.getElementById("text").textContent = "Error";
  });
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