我尝试使用此模块在我的Vue.js测试文件中创建一个下载按钮:
<template>
<div class="container">
<h1>profile</h1>
<button @click="download" class="btn btn-success">download</button>
<h4>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci hic labore nesciunt perspiciatis quibusdam voluptatum! A alias dolores, eligendi fugit molestiae quam quo ratione recusandae ut vel, vitae voluptates! Deserunt!</h4>
<!--<ul v-if="posts && posts.length">-->
<!--<li v-for="post of posts">-->
<!--<p><strong v-text="post.title"></strong></p>-->
<!--<p v-text="post.body"></p>-->
<!--</li>-->
<!--</ul>-->
</div>
</template>
<script>
export default{
data(){
return {
posts: [],
errors: []
};
},
// Fetches posts when the component is created.
created() {
},
methods: {
/**
* Prepare the component.
*/
download() {
var PUBLIC_SERVER_AUTH_TOKEN = "Bearer YYY";
var LOCAL_SERVER_AUTH_TOKEN = "Bearer XXX";
var PUBLIC_SERVER_BASE_URL = 'https://api.xxx.com/api/v1/role?file=xls';
var LOCAL_SERVER_BASE_URL = 'http://xxx.xxx.xxx.xxx:82/api/v1/role?file=xls';
var instance = axios.create({
baseURL: PUBLIC_SERVER_BASE_URL
// baseURL: LOCAL_SERVER_BASE_URL
});
instance.defaults.headers.common['Authorization'] = PUBLIC_SERVER_AUTH_TOKEN;
instance.defaults.headers.common['Content-Type'] = 'text/html; charset=utf-8';
instance.get()
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.xls');
document.body.appendChild(link);
link.click();
}
).catch(function (error) {
if (error.response) {
console.log('error.response');
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
console.log('error.request');
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
console.log('else');
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log('final of catch');
console.log(error.config);
});
}
}
};
</script>
当我在本地使用它时,文件被下载但是当使用“PUBLIC_SERVER_BASE_URL”无法获取文件时,我可以在“POSTMAN”中获得excel文件,当我在网络选项卡中看到chrome调试器时可以看到文件的响应,但不能通过浏览器下载。