使用axios从api下载响应作为文本文件

时间:2020-08-10 17:22:41

标签: reactjs google-chrome axios

所以我正在使用Axios尝试下载文本文件。

我向一个API提出了请求,该API向我提供了文本响应,并且我希望能够下载该文件。我尝试了一些在网上找到的解决方案,并提供了以下用于处理响应的代码。

  const handleGenerate = () => {
    Server.get('sampleurl', {
      responseType: 'blob',
      headers: {
        accept: 'text/plain',
      },
    })
      .then(response => {
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', 'activation_file.txt')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      })
      .catch(error => {
        console.log('Error downloading activation file: ' + JSON.stringify(error))
      })
  }

我在chrome中遇到此错误,如何下载文件?

不允许下载。启动或实例化下载的框架被沙盒化,但是未设置标记“允许下载”。有关更多详细信息,请参见https://www.chromestatus.com/feature/5706745674465280

0 个答案:

没有答案