使用proxy把后端返回的图片域名替换成目标域名
使用proxy把后端返回的图片域名替换成目标域名
proxy 对象用于创建一个对象的代理,是在目标对象之前架设一个拦截,外界对该对象的访问,都必须先通过这个拦截。通过这种机制,就可以对外界的访问进行过滤和改写。
ES6 原生提供 Proxy 构造函数,用来生成 Proxy 实例。
var proxy = new Proxy(target, handler);
target参数表示所要拦截的目标对象,handler参数也是一个对象,用来定制拦截行为。
以下使用示例:
export function newproxy(obj) {// 必须是http开头或者https开头,结尾为'/'// 把host替换成指定数值var reg = /^http(s)?:\/\/(.*?)\//;var ToReplace = "/";let handler = {get: function (target, propKey, receiver) {if (target[propKey]) {if (target[propKey].constructor == Array) {target[propKey] = target[propKey].toString()}if (target[propKey].indexOf("http") !== -1) {target[propKey] = target[propKey].replace(reg, ToReplace);}if (target[propKey].indexOf("http") !== -1 &&target[propKey].indexOf(",") !== -1) {var imglist = target[propKey].split(',');target[propKey] = "";imglist.forEach((element, index) => {if (element && index == 0) {target[propKey] += element.replace(reg, ToReplace);} else {target[propKey] += "," + element.replace(reg, ToReplace);}});}if (target[propKey].indexOf("<img") !== -1 &&target[propKey].indexOf("http") !== -1) {var regContent = /<img [^>]*src=['"]([^'"]+)[^>]*>/gi;target[propKey] = target[propKey].replace(regContent,function (img, src) {var regImg =/<img([^>]*)\ssrc=(['"])(?:[^\2\/]*\/){3}([^\2]+)\2/gi;let newSrc = img.replace(regImg,`<img$1 src=$2${ToReplace}$3$2`);return newSrc;});}}return target[propKey];},};return new Proxy(obj, handler);
}
使用
var newback = newproxy(data); //data为后端返回的数据 data{img:http://1234656/....jpg}
const newImg= newBack.img; //把img的域名替换成/
最新文章
- BIOS的报警声音对应的故障原因
- Git企业开发级讲解(二)
- 振南技术干货集:深入浅出的Bootloader(3)
- linux中mysql下mysqldump命令常见用法详解
- 聚焦车用AI算力,奕行智能EVAS完成超亿元Pre
- 序列化注解脱敏
- mysql 中with的用法(2)
- 卷积神经网络(1)
- Angular 模块介绍及使用(二)
- ubuntu使用xdebug测试php的性能
- css实现鼠标悬停时元素的显示与隐藏
- 微软允许OEM对Win10不提供关闭Secure Boot
- [C++]Leetcode17电话号码的字母组合
- linux rsyslog日志采集格式设定一
- Java可以传入任意类的公共类写法
- 【Shell脚本10】Shell 流程控制
- 人工智能与发电玻璃:未来能源技术的融合