从技术层面来讲,我们可以设置 <img> 标签需要带上cookie等凭据来向后端请求图片资源,后端检测凭据是否合法来决定是否返回相应资源
以 img 标签为例,其它例如 <audio>、<img>、<link>、<script> 和 <video> 均有一个跨域属性 (crossOrigin property),它允许你配置元素获取数据的 CORS 请求。
设置 crossorigin="use-credentials"表示请求将带上凭据:
<img crossorigin="use-credentials" src="https://asset.xxx.xxx/cxk.jpeg" alt="">
不能通过js代码设置跨域的domain:
Note: The domain must match the domain of the JavaScript origin. Setting cookies to foreign domains will be silently ignored.
https://stackoverflow.com/a/6761443
用于演示携带的 cookie
因为是跨域请求,这时候要浏览器带上cookie就需要设置以下红色框的内容,又因为是 https 请求,所以要设置绿框的内容

web服务器的设置(nginx):
add_header 'Access-Control-Allow-Origin' '具体的某个源';
add_header 'Access-Control-Allow-Credentials' 'true';
最终可以看到请求中携带了cookie:

网友评论