【前端】解決訪問api圖片403禁止訪問問題

當咱們訪問某些接口的時候,解決了接口跨域問題,然而又出現了圖片403禁止訪問問題

這種設計,是api廠商正常保證本身的服務器不被刷流量php

解決這個問題的姿式

利用這個網站來處理給你返回的圖片api地址
https//image.weserv.nl/?url=imgurlios

https://images.weserv.nl/?url...
在你的圖片前面加上這個連接axios

使用方法:把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');
    }
}

整個組件代碼

配置代理api

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>
相關文章
相關標籤/搜索