【前端】解决访问api图片403禁止访问问题

当我们访问某些接口的时候,解决了接口跨域问题,然而又出现了图片403禁止访问问题

这种设计,是api厂商正常保证自己的服务器不被刷流量

解决这个问题的姿势

利用这个网站来处理给你返回的图片api地址
https//image.weserv.nl/?url=imgurl

https://images.weserv.nl/?url...
在你的图片前面加上这个链接

使用方法:把api图片连接提取出来,使用下面方法过滤

<div>图片:<img :src="item.img" :alt="item.hero_title"></div>

getImage(url){
    console.log(url);
    // 把现在的图片连接传进来,返回一个不受限制的路径
    if(url !== undefined){
        return url[0].replace(/http\w{0,1}:\/\/p/g,'https://images.weserv.nl/?url=p');
    }
}

整个组件代码

配置代理

        proxyTable: {
            '/v1': {
                target: 'http://hero.shudong.wang/',
                changeOrigin: true
            },
            '/api': {
                target: 'https://news-at.zhihu.com/',
                changeOrigin: true,
                pathRewrite: {
                    '^/api': '/api/4'
                }
            }
        },

        每次访问 localhost:8080/api/news/latest
             pathRewrite: {
                    '^/api': '/api/4'
                }
        每次遇到 以api 开头的url ,自动转化成 api/4
        api/news/latest  -> api/4/news/latest 
        相当于https://news-at.zhihu.com/api/4/news/latest
<template>
    <div>
        <div v-for="(item,index) in stories" :key="index">
            <div>名字:{{item.title}}</div>
            <div>描述:{{item.ga_prefix}}</div>
            <div>图片:<img :src="getImage(item.images)" :alt="item.title"></div>
        </div>
    </div>
</template>

<script>
    import axios from 'axios';

    export default {
        data(){
            return{
                stories:{}
            }
        },
        created(){
            this.getHero()
        },
        methods:{
            getHero(){
                // https://news-at.zhihu.com/api/4/news/latest
                // axios.get('http://hero.shudong.wang/v1/db.php')
                axios.get('/api/news/latest')
                .then(res=>{
                    this.stories = res.data.stories;
                })
            },
            getImage(url){
                console.log(url);
                // 把现在的图片连接传进来,返回一个不受限制的路径
                if(url !== undefined){
                    return url[0].replace(/http\w{0,1}:\/\/p/g,'https://images.weserv.nl/?url=p');
                }
            }
        }
    }
</script>


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值