从节点js服务器直接下载vue客户端文件无效

时间:2019-12-13 15:10:53

标签: javascript node.js vue.js axios

好吧,所以我已经尝试了2天了,以HTTP请求在浏览器中将音频文件作为直接下载从节点js后端(端口8081)发送到vue js客户端前端(端口8080)(使用axios)。

关于堆栈溢出的一些主题,但没有一个解决了我的问题,我可能在某个地方犯了一个错误,但我似乎看不出确切的位置。

我的浏览器/客户端收到响应,但没有将其转换为直接下载,这是它的外观:

{data: "ID3#TSSELavf57.71.100���…UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU", status: 200, statusText: "OK", headers: {…}, config: {…}, …}
config: {url: "http://localhost:8081/api/tracks/download/5df305bc6cea85c8eac5d3e6", method: "get", headers: {…}, transformRequest: Array(1), transformResponse: Array(1), …}
data: "ID3#TSSELavf57.71.100���..."
headers: {cache-control: "public, max-age=0", content-length: "9775064", content-type: "audio/mpeg", last-modified: "Fri, 13 Dec 2019 03:30:04 GMT"}
request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}
status: 200
statusText: "OK"
__proto__: Object

我需要设置代理吗,我不确定我是否完全了解如何正确执行此操作?我真的一直在努力让它工作大声笑

以下是代码:

node.js服务器下载路径

router.get('/download/:id', async (req, res) => {
  const tracks = await loadTracksCollection();
  var id = new mongodb.ObjectID(req.params.id);
  var track = await tracks.findOne({ _id: id });
  var trackPath = String(track.path);
  var trackName = String(track.user + ' - ' + track.name + '.mp3');
  res.download(trackPath, trackName, (err) => {
    if (err) {
      console.error(err);
      return ;
    } else {
    tracks.updateOne({ _id: id }, { $inc: { downloadCount: 1 } });
    // return res.status(200).send('The download should start ...')
    }
  });
});

vue.js按钮组件

<template>
  <v-btn @click="download" depressed block color="accent"><unicon name="import" fill="white" /></v-btn>
</template>

<script>
import axios from 'axios'

export default {
  props: {
    fileId: {
      required: true,
      type: String
    }
  },
  methods: {
    download() {
      axios.get(process.env.VUE_APP_AUDIO_API_URL + '/api/tracks/download/' + this.fileId)
           .then(response => {
             console.log(response)
           })
           .catch(error => {
             console.error(error)
           })
    }
  }
}
</script>

让我知道是否需要更多代码!

非常感谢!

2 个答案:

答案 0 :(得分:0)

您需要在axios中更改responseType ...

axios({
    method: 'GET',
    url: process.env.VUE_APP_AUDIO_API_URL + '/api/tracks/download/' + this.fileId,
    responseType: 'arraybuffer'
}).then(response => {
   console.log(response.data)
}).catch(error => {
   console.error(error)
})

答案 1 :(得分:0)

好的,这似乎是一个复杂的主题,但是我找到了解决方案,在这里您可以进行:

      this.$axios({
          method: 'GET',
          url: // ur backend api url,
          responseType: 'arraybuffer'
        })
        .then(response => {
          var blob = new Blob([response.data], {type: response.headers['content-type']})
          var link = document.createElement('a')
          link.href = window.URL.createObjectURL(blob)
          link.download = // name the downloaded file
          link.click()
        })
        .catch(error => { 
          // whatever
        })
        .finally(() => {
          // whatever
        }