Access to XMLHttpRequest at 'http://localhost:8001/****/****/download'
from origin 'http://localhost:9528' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
请求js 代码:
downloadStudent() {
return axios.get(process.env.VUE_APP_BASE_API + `/student/query/download`, { responseType: 'blob' })
}
后端没问题,可以显示查询出来的信息。
/**
* 导出所有学生信息
* 通过Excel导出
*/
@GetMapping("/****/****")
public void download(HttpServletResponse response){
tbSchoolService.download(response);
}
原因:由于设置了权限框架,该axios请求被拦截。造成跨域的问题
解决方法:设置请求头
在request.js 文件设置
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
// create an axios instance
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
// withCredentials: true, // send cookies when cross-domain requests
timeout: 5000 // request timeout
})
// request interceptor
service.interceptors.request.use(
config => {
if (store.getters.token) {
config.headers['X-Token'] = getToken()
config.headers['Authorization'] = getToken()
}
return config
},
error => {
// do something with request error
console.log(error) // for debug
return Promise.reject(error)
}
)
在编写vue,页面添加
import { getToken } from '@/utils/auth'
请求方法,添加 getToken()
studentApi.downloadStudent(getToken()).then(res => {}
后端几乎不用修改
请求结果: