場景很簡單,主要是接口需要認證包括圖片,但是使用了前后端分離的模式,所以直接基於src模式指定圖片是有問題的(權限)
解決方法
認證模式使用cookie
但是在現有的設計中不太合理,也比較費事,因為使用了spring cloud 認證在gateway
重新請求指定src圖片數據
理論上肯定不能基於http 請求模式了,但是可以變向的使用http,基於ajax 請求獲取數據,並賦值到img屬性(blob,以及base64都是可行的)
實際上直接基於URL.createObjectUR也是可行的,而且比較靈活
簡單運行
- index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>demo</title>
</head>
<body>
<img id="img" demosrc="/app.png" style="width: 200px;height: 200px;" alt="">
<script>
var img = document.getElementById('img');
var url = img.getAttribute('demosrc');
var request = new XMLHttpRequest();
request.responseType = 'blob';
request.open('get', url, true);
request.setRequestHeader('token', "ddddddddd");
request.onreadystatechange = e => {
if (request.readyState == XMLHttpRequest.DONE && request.status == 200) {
console.log(request.response)
img.src = URL.createObjectURL(request.response);
img.onload = () => {
URL.revokeObjectURL(img.src);
}
}
};
request.send(null);
</script>
</body>
</html>
- nginx 配置
使用次方法可以解決一些跨域的場景
worker_processes 1;
user root;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
lua_need_request_body on;
gzip on;
resolver 114.114.114.114 ipv6=off;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
server {
listen 80;
server_name localhost;
charset utf-8;
default_type text/html;
location / {
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
- docker-compose 文件
version: "3"
services:
app:
image: openresty/openresty:alpine
volumes:
- ./nginx.conf:/usr/local/openresty/nginx/conf/nginx.conf
- ./index.html:/usr/local/openresty/nginx/html/index.html
- ./app.png:/usr/local/openresty/nginx/html/app.png
ports:
- "80:80"
- 效果
一些說明
為了性能以及安全,使用createObjectURL創建的對象,在不使用的時候應該釋放掉可以使用URL.revokeObjectURL
參考資料
https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL
https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL
https://github.com/jcblw/image-to-blob