Read the body of a Fetch Promise

前端 未结 3 1178
没有蜡笔的小新
没有蜡笔的小新 2020-12-04 21:15

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 sto

相关标签:
3条回答
  • 2020-12-04 21:32

    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()))
    
    0 讨论(0)
  • 2020-12-04 21:40

    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.

    0 讨论(0)
  • 2020-12-04 21:42

    @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/

    0 讨论(0)
提交回复
热议问题