因項目中安全測評的需要,請求圖片時要求添加token,方法如下:
在項目中循環渲染的img標簽中的圖片要顯示,src需要加請求頭token(正常情況下,后端直接返回src的url)
1. 自定義子組件authImg,在這發送請求,獲取img地址
<template>
<img ref="img" />
</template>
<script>
export default {
name: 'authImg',
props: {
authSrc: String
},
computed: {
// 拿到token值,登錄成功后由后台返回的
token() {
// 這里我把登錄之后拿到的token放到了vuex中
return this.$store.state.commonState.m_token;
}
},
mounted() {
},
methods: {
// 攜帶token請求img的src
getImgSrcByToken() {
// Object.defineProperty()方法會直接在一個對象上定義一個新屬性,或者修改一個對象的現有屬性,並返回此對象
Object.defineProperty(Image.prototype, 'authSrc', {
// 可寫
writable: true,
// 可枚舉
enumerable: true,
// 若configurable設為false,那就不可以delete了
configurable: true
});
let img = this.$refs.img;
let request = new XMLHttpRequest();
request.responseType = 'blob';
request.open('get', this.authSrc, true);
request.setRequestHeader('token', this.token);
request.onreadystatechange(e => {
if(request.readyState == XMLHttpRequest.DONE && request.status == 200) {
// URL.createObjectURL() 靜態方法會創建一個 DOMString,其中包含一個表示參數中給出的對象URL,這個新的URL對象表示指定的File對象或blob對象
img.src = URL.createObjectURL(request.response);
img.onload = () => {
// 在每次調用 createObjectURL() 方法時,都會創建一個新的 URL 對象,即使你已經用相同的對象作為參數創建過。當不再需要這些 URL 對象時,每個對象必須通過調用 URL.revokeObjectURL() 方法來釋放。
URL.revokeObjectURL(img.src);
}
}
});
request.send(null);
},
},
}
</script>
2. 父組件中調用
<authImg :authSrc="baseurl + '/download.do?id='+ files.name + '&height=60'" alt=""></authImg>
