【问题标题】:How can I open csv file received from axios get response in new window如何打开从 axios 收到的 csv 文件在新窗口中获取响应
【发布时间】:2020-12-09 08:04:56
【问题描述】:

美好的一天。 我有一个这样的结构,它奏效了。

       axios.post(url, testsToExportToCsv)
            .then(response => {
                let win = window.open(response.data.uri, '_blank');
                win.focus();
            });

但是后来在项目中实现了一些带有标头的令牌,所以我不能使用普通的 window.open - 因为安全性,它不会让我这样做。

我重写了那个代码:

        axiosWithHeaders.post(url, testsToExportToCsv)
            .then(response => {
                axiosWithHeaders
                    .get(response.data.uri)  // receiving the link
                    .then(response => {
                        console.log("response", response)
                        // and here I need to put some code to open CSV from response.data
                     
                    })

            });

请不要将axiosWithHeaders 计入计数 - 它工作得很好,它只是下面带有令牌的 axios。

所以,我成功获得了 CSV 文件作为响应。但我需要在新窗口中将其显示为 CSV,如何做到这一点?

我试过类似的

                    let win = window.open(response.data);
                     win.focus();

但它不起作用。

【问题讨论】:

    标签: javascript reactjs axios token


    【解决方案1】:

    好吧,在花费了几个小时后,这工作了

            axiosWithHeaders.post(url, testsToExportToCsv)
                .then(response => {
                    nameOfTheCsv = response.data.name;
                    axiosWithHeaders
                        .get(response.data.uri, {responseType: 'blob'})
                        .then(response => {
                            const downloadUrl = window.URL.createObjectURL(new Blob([response.data]));
                            const link = document.createElement('a');
                            link.href = downloadUrl;
                            link.setAttribute('download', nameOfTheCsv);
                            document.body.appendChild(link);
                            link.click();
                            link.remove();
                        }).catch(err => console.log(err));
                })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      相关资源
      最近更新 更多