解决方案总结:
1、打开新网页,浏览器输入:chrome://flags/#block-insecure-private-network-requests,改成Disabled,重启浏览器。(需要客户手动操作,不采纳)
2、给img添加crossOrigin 属性(此方法不好用,can i use显示浏览器不支持img 标签的 src跨域问题
3、<meta name="referrer" content="no-referrer-when-downgrade" /> 参考:change referrer-policy in react js(未采用不适合项目)
4、前端设置方法( 参考HTTP请求之referrer与Referrer-Policy)
① 通过Referrer-Policy HTTP header设置:Referrer-Policy: origin
②通过<meta>元素改变Referrer Policy,直接修改名为referrer的内容
<meta name="referrer" content="origin">
③ 给 <a> <area><img><iframe> 或<link>元素设置referrerpolicy属性
<a href="http://example.com" referrerpolicy="origin">
④ 如需设置不显示referrer信息,可以给 <a><area> <link>元素设置rel的链接关系。
<a href="http://example.com" rel="noreferrer">
react,img标签src获取图片提示跨域,
<img src={originSrc[i]} key={i} />
控制台提示:
Access to image at 'http://127.0.0.1:15284/C:/Users/28929/camera_0.jpg?1655275037147' from origin 'http://171.5.37.13' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space `local`.
Access to image at 'http://127.0.0.1:15284/C:/Users/28929/camera_1.jpg?1655275037147' from origin 'http://171.5.37.13' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space `local`.
分析:
1、谷歌94版本上基本上端口号4位成功,5位失败,此时误以为是端口5位数导致(端口随机生成),但随着操作次数增多发现,4位端口号也会失败,如下:
Access to image at 'http://127.0.0.1:1042/C:/Users/28929/camera_0.jpg?1655279684455' from origin 'http://171.5.37.13' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space `local`.
2、谷歌84版本,4、5位端口号都获取图片成功,查看资料得知Chrome 新的默认 Referrer-Policy : strict-origin-when-cross-origin
3、后来又看到一篇文章:HTTP请求之referrer与Referrer-Policy ,对比成功和失败发现
失败:
General
Request URL: http://127.0.0.1:23246/C:/Users/28929/camera_0.jpg?1655279684455
Referrer Policy: strict-origin-when-cross-origin
Response Headers
Referer: http://171.5.37.13/
...
成功:
General
Request URL: http://127.0.0.1:23382/C:/Users/28929/camera_0.jpg?1655280203114
Request Method: GET
Status Code: 200 OK
Remote Address: 127.0.0.1:23382
Referrer Policy: strict-origin-when-cross-origin
Response Headers
...
Accept: image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
Connection: keep-alive
Host: 127.0.0.1:23382
Referer: http://172.27.1.144/
...
试了一把,诶?
<img src={originSrc[i]} referrerpolicy='origin' key={i} />
好像靠谱,至此问题终于解决。
总结写在文章最开头,方便大家快速找到解决方案。
本文总结了解决Chrome高版本浏览器中img标签通过src属性跨域获取图片失败的几种方法,包括更改浏览器设置、添加crossOrigin属性、设置Referrer-Policy等。在分析了不同版本Chrome的行为和错误提示后,找到了成功解决该问题的方案。
482

被折叠的 条评论
为什么被折叠?



