You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

URL含.png后缀后参数时img-src无法加载图片,求非字符串分割方案

解决方案汇总

1. 通过Fetch API转Blob绕防盗链

Fandom的防盗链会检查请求的来源头,直接用img或background-image请求时,来源是你的站点,会被拦截。可以用Fetch模拟浏览器请求头获取图片Blob,再转成本地可访问的ObjectURL:

fetch('https://static.wikia.nocookie.net/valorant/images/9/9c/Raze_icon.png/revision/latest?cb=20230523180834', {
  headers: {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
  }
})
.then(resp => resp.blob())
.then(blob => {
  const objectURL = URL.createObjectURL(blob);
  // 给img标签赋值
  document.querySelector('img').src = objectURL;
  // 给div背景图赋值
  document.querySelector('.bg-box').style.backgroundImage = `url(${objectURL})`;
  // 可选:使用后释放URL(浏览器会自动回收,手动释放更节约资源)
  // setTimeout(() => URL.revokeObjectURL(objectURL), 5000);
})
.catch(err => console.error('图片加载失败:', err));

2. 后端代理转发请求

如果前端方案受跨域限制,可以搭建简单的后端代理,由后端请求图片再返回给前端(以Node.js/Express为例):

const express = require('express');
const axios = require('axios');
const app = express();

app.get('/proxy-image', async (req, res) => {
  try {
    const imgUrl = req.query.url;
    const resp = await axios.get(imgUrl, { responseType: 'stream' });
    res.set('Content-Type', resp.headers['content-type']);
    resp.data.pipe(res);
  } catch (err) {
    res.status(404).send('图片加载失败');
  }
});

app.listen(3000, () => console.log('代理服务运行在3000端口'));

前端调用示例:

<img src="http://localhost:3000/proxy-image?url=https://static.wikia.nocookie.net/valorant/images/9/9c/Raze_icon.png/revision/latest?cb=20230523180834" />

3. 调用Fandom官方API获取合法URL

这是最合规的方式,通过Fandom的MediaWiki API获取图片的直接访问地址:

// 图片文件名是File:Raze_icon.png,对应目标站点为valorant.fandom.com
fetch('https://valorant.fandom.com/api.php?action=query&titles=File:Raze_icon.png&prop=imageinfo&iiprop=url&format=json')
.then(resp => resp.json())
.then(data => {
  const pageId = Object.keys(data.query.pages)[0];
  const validImgUrl = data.query.pages[pageId].imageinfo[0].url;
  document.querySelector('img').src = validImgUrl;
  document.querySelector('.bg-box').style.backgroundImage = `url(${validImgUrl})`;
})
.catch(err => console.error('API请求失败:', err));

原因说明:Fandom带/revision/latest参数的链接会校验请求来源,浏览器直接打开时Referer是Fandom自身,所以允许访问;而站点内的img/background-image请求Referer是你的站点,触发防盗链拦截。

内容的提问来源于stack exchange,提问作者silj6

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 22:13:19