Read the body of a Fetch Promise

倖福魔咒の 提交于 2019-12-02 21:48:51

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.

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

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