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

Time:01-01

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 ?

CodePudding user response:

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";
  });

CodePudding user response:

The "response" that comes back from the fetch is an object that has more than just the data in the response. It's a Response object which means it contains the status code (like 200) as well as the data. Typically you can get the data from the response using response.json() if it's JSON format, or response.text() if it's text. These functions are asynchronous so also return a Promise. So your code can look like this:

fetch("/myaction", datos)
.then(function (response) {
  return response.text();   // a Promise that will resolve to the data
})
.then(function (text) {
  document.getElementById("text").innerHTML = text;
})
.catch(() => {
  document.getElementById("text").innerHTML = "Error";
});

Whenever you see a string looking like [object Object] it means you are seeing a Javascript object that doesn't have a meaningful toString() function so that's the best it can do to show you the value. If you're not sure what kind of object it is, a good debugging technique is to output it using console.log(obj) so you can see what it looks like. That usually gives you a clue about what you really are working with.

  • Related