ReactJS:如何解析从REST API发送的文件的响应并显示它们?

时间:2021-11-01 14:05:13

Using ReactJS, I have a GET request working with fetch method, and the REST API responds with a few files. How would they be sent to me?

使用ReactJS,我有一个使用fetch方法的GET请求,REST API使用一些文件进行响应。他们将如何被发送给我?

Meaning, can it be parsed with response.json(), so that it can be displayed as actual files from REST API and also be downloaded to local drive?

这意味着,是否可以使用response.json()进行解析,以便它可以从REST API显示为实际文件,也可以下载到本地驱动器?

Here is the method that makes the GET request:

以下是发出GET请求的方法:

  sendFileRequest() {

      ...

      return dispatch => {
      dispatch({
        type: 'FETCH_API'
      });

      return fetch('http://11.22.33.44:8080/receive/files', getRequest)
      .then(response => response.json()) //Could I do .json() with files being the response?
      .then(APIfiles => {
        //How can I parse the files returned and display them for download to local drive?
      })
  }

1 个解决方案

#1


0  

fetch({}).then(res => res.json()) or fetch({}).then(res => res.text()), it depend on the content-type of your response.

fetch({})。then(res => res.json())或fetch({})。then(res => res.text()),它取决于你的响应的内容类型。

if your contentType is application/json, you should use res.json(),

如果你的contentType是application / json,你应该使用res.json(),

if your contentType is text/plain, you should use res.text().

如果你的contentType是text / plain,你应该使用res.text()。

you can check the doc here.

你可以在这里查看文档。

Since your server just return a file, I think you should use res.text().

由于您的服务器只返回一个文件,我认为您应该使用res.text()。

#1


0  

fetch({}).then(res => res.json()) or fetch({}).then(res => res.text()), it depend on the content-type of your response.

fetch({})。then(res => res.json())或fetch({})。then(res => res.text()),它取决于你的响应的内容类型。

if your contentType is application/json, you should use res.json(),

如果你的contentType是application / json,你应该使用res.json(),

if your contentType is text/plain, you should use res.text().

如果你的contentType是text / plain,你应该使用res.text()。

you can check the doc here.

你可以在这里查看文档。

Since your server just return a file, I think you should use res.text().

由于您的服务器只返回一个文件,我认为您应该使用res.text()。