Read the body of a Fetch Promise

六月ゝ 毕业季﹏ 提交于 2019-12-03 08:08:52

问题


I'm sure this has a simple answer, but for the life of me I can't figure out how to do it.

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)

Does anyone have any suggestions for how I can retrieve this info from the response body on the client side?

EDIT:

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

EDIT 2:

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


回答1:


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.




回答2:


@GabeRogan gave me the answer (and I had a typo, as expected)

Here's my updated code for the front end which returns the response body text:

Client.upload(this.file).then(response => response.text())
  .then((body) => {
    console.log(body);
  });

body is a string that reads "Unique File Name: [FILE-NAME]"

EDIT:

Here's a good explanation of the Fetch API and reading the response you get from the promise object: https://css-tricks.com/using-fetch/




回答3:


You can also use async/await:

When returning json content:

Client.upload(this.file).then(async r => console.log(await r.json()))

or just returning in textual form:

Client.upload(this.file).then(async r => console.log(await r.text()))


来源:https://stackoverflow.com/questions/43903767/read-the-body-of-a-fetch-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!