如何在不设置响应类型的情况下使用 Node + Express 从 http get 响应创建文件

How to create a file from an http get response using Node + Express without setting the response type

我正在使用 axios 从 Jira 服务器下载文件,但是当我将请求类型设置为 'stream' 时,Jira 的响应表明我未通过身份验证。删除后,我收到以下响应(摘录):

v�Ģ ��-��[��T��j��1c��N{��;&��o����Pvwf=����������P��V4��_��T��};��J$W ��O��|��M\��Oʥ ��L/t%��N����/|����g9i;��^����N��|1b��Q ? ... ��w��A��,��q��#����}V��)+��6gO��3��5$�}8"�bm���;��P�.�m?������zo l�v�G)���,�E7id�JN}�[ �r��Z���)�������o��F�ZN��O�FD���/�����G�QяD����mw�� M��0A��_0�&���Jî!�m����Za �Q����������ƃ�S�����To��3D ��#:��`g��]��|y%Fè ������D

使用下面的代码:

axios.get('http://localhost:8080/secure/attachmentzip/' + req.body.issue.id + ".zip",                             
                            {
                                auth: {
                                    username: '-',
                                    password: '-'
                                } 
                            }
                            )
                                .then(function (response) {
                                    console.log(response.data)
                                     })
                                .catch(function (error) {
                                    console.log(error);
                                })

是否可以根据上述响应创建文件?

在处理文件或二进制数据时,我在过去使用 axios 时遇到过几个问题,我建议使用 requestrequest-promisegot

const request = require('request-promise');
const fs = require('fs').promises;

request.get('http://localhost:8080/secure/attachmentzip/' + req.body.issue.id + ".zip", {
    auth: {
        username: '-',
        password: '-'
    },
    encoding: null // important to avoid utf8 conversion
})
.then(buffer => fs.writeFile('file.zip', buffer)) // fs.promises
.then(() => console.log('saved'))
.catch(console.error)

虽然如果你正在下载文件,但如果文件很大,最好使用流。

const request = require('request'); // better to use request when using streams
const fs = require('fs');

request.get('http://localhost:8080/secure/attachmentzip/' + req.body.issue.id + ".zip", {
    auth: {
        username: '-',
        password: '-'
    }
}).pipe(fs.createWriteStream('file.zip'))

注意:无法测试 URL,无法为您提供特定于 axios 的解决方案。