javascript - how can i print a response from server using express and fetch? - Stack Overflow

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

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 ?

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 ?

Share Improve this question edited Dec 31, 2021 at 17:19 user23232512 asked Dec 31, 2021 at 17:13 user23232512user23232512 331 silver badge6 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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

The "response" that es 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745654942a4638487.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信