Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

javascript - Read the body of a Fetch Promise

I have the following express endpoint for uploading to Google Cloud storage. It works great and the response from the google api gives me a unique file name that I want to pass back to my front end:

app.post('/upload', (req, res) => {
  var form = new formidable.IncomingForm(),
  files = [],
  fields = [];

  form
    .on('field', function(field, value) {
      fields.push([field, value]);
    })
    .on('file', function(field, file) {
      files.push([field, file]);
    })
    .on('end', function() {
      console.log('-> upload done');
    });
  form.parse(req, function(err, fields, files){
    var filePath = files.file.path;
    bucket.upload(filePath, function(err, file, apiResponse){
      if (!err){
        res.writeHead(200, {'content-type': 'text/plain'});
        res.end("Unique File Name:" + file.name);
      }else{
        res.writeHead(500);
        res.end();
      }
    });
  });

 return;
});

I reach this endpoint by calling a short function which passes the file to it:

function upload(file) {
  var data = new FormData();
  data.append('file', file);
  return fetch(`upload`,{
    method: 'POST',
    body: data
  });
}

const Client = { upload };
export default Client;

This function is called from my front end like this:

Client.upload(this.file).then((data) => {
  console.log(data);
});

This final console.log(data) logs the response to the console. However, I don't see anywhere the response that I wrote in ("Unique File Name:" + file.name)

How I can retrieve this info from the response body on the client-side?

The data looks like this when I console.log it:

Screenshot of the data console.log

This is the response I get when I POST a file to my endpoint using Postman:

Screen shot of response using Postman

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Notice you're dealing with a Response object. You need to basically read the response stream with Response.json() or Response.text() (or via other methods) in order to see your data. Otherwise your response body will always appear as a locked readable stream. For example:

fetch('https://api.ipify.org?format=json')
.then(response=>response.json())
.then(data=>{ console.log(data); })

If this gives you unexpected results, you may want to inspect your response with Postman.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...