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

ReactJS: How to parse response of files sent from REST API and display them?

本文关键字:响应 文件 显示 何解析 API REST ReactJS      更新时间:2023-09-26

使用ReactJS,我有一个GET请求与fetch方法一起工作,REST API用几个文件响应。他们怎么被送到我这里来?

意思是,它可以用response.json()解析,以便它可以显示为来自REST API的实际文件,也可以下载到本地驱动器?

下面是发出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?
      })
  }

fetch({}).then(res => res.json())fetch({}).then(res => res.text()),这取决于您的回复的内容类型。

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

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

你可以在这里查看文档。

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

您需要与负责开发API的人员检查可能的响应内容类型。

你需要知道的是REST并不固定于JSON。这都是关于资源的,因此,您可以接收XML、纯文本、文件等。