Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 761
quicklikerabbit Avatar asked May 10 '17 22:05

quicklikerabbit


People also ask

How do you read a fetch body?

To read the body of a Fetch promise with JavaScript, we can use the json method. const f = async () => { const response = await fetch("https://api.ipify.org?format=json"); const data = await response. json(); console. log(data); };

How do you read a body response?

To read the body of the response, we need to access its Body property first. We can access the Body property of a response using the ioutil. ReadAll() method. This method returns a body and an error.

What is a fetch promise?

A fetch() promise only rejects when a network error is encountered (which is usually when there's a permissions issue or similar). A fetch() promise does not reject on HTTP errors ( 404 , etc.). Instead, a then() handler must check the Response. ok and/or Response.

What is fetch () in JavaScript?

The fetch() method in JavaScript is used to request to the server and load the information on the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise. Syntax: fetch('url') //api for the get request .


4 Answers

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.

like image 87
Gabe Rogan Avatar answered Oct 17 '22 19:10

Gabe Rogan


I had a typo in my code as pointed out by GabeRogan in this comment:

Ok awesome. To be quite honest I have absolutely no clue why you're getting undefined, except that it might be some sort of misspelling error?

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]

Here's a good explanation of the Fetch API and reading the response you get from the promise object: Css tricks: Using Fetch.

like image 27
quicklikerabbit Avatar answered Oct 17 '22 17:10

quicklikerabbit


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()))
like image 22
spedy Avatar answered Oct 17 '22 19:10

spedy


If you are getting "undefined" for data and you are doing something with the response, make sure to return the response.

I was doing something like this

fetch(URL)
    .then(response => {
        response.text();
        console.log(response.statusText);
    })
    .then(data => console.log(data)); // got "undefined"

Return response object: return response.text();

fetch(URL)
    .then(response => {
        console.log(response.statusText);
        return response.text();
    })
    .then(data => console.log(data)); // got data
like image 3
Sivaraman Avatar answered Oct 17 '22 17:10

Sivaraman