Vue中使用el-uploda上传文件时出现跨域问题
主要在我spring boot后端整合shiro进行权限控制时出现的
问题如下,在发起请求后浏览器一直提示出现跨域拦截
前端vue上传代码如下,报错提示头部缺少了Access-Control-Allow-Origin
前端vue代码如下
<el-upload
class="uploadTemplate"
name="file1"
:action="uploadExcel()"
:on-success="uploadSuccess"
:on-error="uploadError"
:on-change="getFile"
multiple >
<el-button class="batch-add-button" icon="el-icon-s-unfold">批量添加</el-button>
</el-upload>
第一种解决思路:
猜想:由于我后端是spring boot+shiro进行管理的,所以猜测可能是el-upload的请求发送是不带token的,所以无法通过shiro的认证。
查看我能正常访问的url请求头,如下
查看请求头,在请求头确实没有 Authorization
所以我在请求头中加入了Authorization,在el-upload中加入了头部信息 :headers = “myHeaders”,如下
前端vue代码如下
<el-upload
class="uploadTemplate"
name="file1"
:headers="myHeaders"
:action="uploadExcel()"
:on-success="uploadSuccess"
:on-error="uploadError"
:on-change="getFile"
multiple >
<el-button class="batch-add-button" icon="el-icon-s-unfold">批量添加</el-button>
</el-upload>
myHeaders: {'Access-Control-Allow-Origin':'*'},
上传方法,从localStorage中获取token的值,然后赋值给Authorization
//上传excel文件
uploadExcel() {
let token = localStorage.getItem('set_token');
this.myHeaders.Authorization = token;
let url = 'http://192.168.x.xxx:8080/examination-room-arrangement/post/import/excel/' + this.examPlanId;
return url;
},
第二种解决思路:
在el-upload中采用自定义请求 :http-request
myUpload方法是上传方法,on-change是获取文件(相当于监听)
getFile(file, fileList) {
this.file = file;
},
myUpload(content) {
debugger;
let fileFormData = new FormData();
fileFormData.append('file', this.file); //file是值,就是要传的文件,
let url = 'http://192.168.xx.xxx:8080/examination-room-arrangement/post/import/excel/' + this.examPlanId;
postUploadExcel(url, fileFormData, {headers: {'Content-Type': 'multipart/form-data'}})
/* , 'Access-Control-Allow-Origin': '*' */
.then(res => {
if (res.code === 200) {
this.$message({
message: '上传成功',
type: 'success'
});
this.queryExamVenue();
} else {
this.$message({
message: '上传失败',
type: 'error'
});
}
})
.catch(res => {
this.$message({
message: '上传失败1',
type: 'error'
});
});
第三种思路:
不折腾了,在shiro中直接对该请求放行,如红色划线那部分,将该上传请求url直接添加为 anon