简体   繁体   English

如果由于用户不存在而导致对API的后端GET请求失败,如何显示404页面? 前端和后端分离

[英]How to display 404 page if a back-end GET request to an API fails because user doesn't exists? Separated front-end and back-end

I have an application that uses JavaScript with Vue.js for the front-end and PHP with Laravel for the back-end. 我有一个将JavaScript与Vue.js一起用于前端,将PHP与Laravel一起用于后端的应用程序。

Right now, when I make a GET request from my front-end to my back-end on URL /getSummoner/{summonerName} , I make another GET request from my back-end to a third party API in order to get the details for a user with a certain summoner name like this: 现在,当我从前端到后端通过URL /getSummoner/{summonerName}发出GET请求时,我从后端向第三方API发出了另一个GET请求,以获取有关的详细信息具有特定召唤者名称的用户,如下所示:

public function getSummoner($summonerName){

        $summoner = Summoner::where('summoner_name', $summonerName)->first();

        if ($summoner === null) {
            $apiKey = env("RIOT_API_KEY");
            $region = env("EUW");

            $getSummonerInfo = file_get_contents($region . "/lol/summoner/v4/summoners/by-name/" . $summonerName . "?api_key=" . $apiKey);
            $summonerInfo = json_decode($getSummonerInfo);

            $summoner = new Summoner();
            $summoner->summoner_name = $summonerName;
            $summoner->summoner_info = json_encode($summonerInfo);

            $summoner->save();
        } else {
            $summonerInfo = json_decode($summoner->summoner_info);
        }

        return response()->json([
            'summonerInfo' => $summonerInfo,
        ], 201);

}

And then I return a JSON response to my front-end with the summoner info. 然后,我将带有召唤者信息的JSON响应返回到我的前端。 This all works fine and dandy as long as a user with that summoner name exists. 只要存在具有该召唤者名称的用户,这一切都可以正常工作。 If he doesn't exists, the GET request fails so the rest of my function fails and in return I get an error on my front-end. 如果他不存在,那么GET请求将失败,因此我的其他功能也会失败,并且作为回报,我的前端会出现错误。

So I am wondering what am I supposed to do to get a 404 page on the front-end if my back-end GET request doesn't go through? 所以我想知道如果我的后端GET请求没有通过,我应该怎么做才能在前端获得404页面? Both on the front and back-end. 在前端和后端。 I assume I need to return some sort of response from the back-end and then based on that response do something on the front-end? 我假设我需要从后端返回某种响应,然后根据该响应在前端执行某些操作?

Here's my front-end: 这是我的前端:

<template>
    <div>{{ summonerInfo }}</div>
</template>

<script>
import axios from 'axios'
import router from '../router'

export default {
    data(){
        return {
            summoner: this.$route.params.summonerName,
            summonerInfo: '',
        }
    },
    methods: {
        user(action){
            let trimmedSummoner = this.summoner.replace(/\s+/g, '');
            axios.get('/' + action + 'Summoner/' + trimmedSummoner)
            .then((response) => {
                this.summonerInfo = response.data.summonerInfo
            })
            .catch(function (error) {
                console.log(error);
            })
        }
    },
    watch:{
        $route (to, from){
            this.summoner = this.$route.params.summonerName
            this.user('get')
        }
    },
    mounted(){
        this.user('get')
    }
}
</script>

One poor mans way of doing this would be to wrap your request in a try / catch . 一个穷人的方法是将您的请求包装在try / catch This way, when you request fails, you have the opportunity to catch it and redirect. 这样,当您的请求失败时,您就有机会捕获并重定向。 Downside to this method is that it doesn't give you any info on what the status code is (4xx vs 5xx, etc...). 这种方法的缺点是它不会为您提供有关状态码是什么的任何信息(4xx与5xx等)。

However, a proper solution would be to use Http Interceptors to handle this. 但是,一种适当的解决方案是使用Http Interceptor来处理此问题。

How can you use axios interceptors? 如何使用axios拦截器?

Here is another example using try / catch approach: 这是另一个使用try / catch方法的示例:

https://gist.github.com/fgilio/230ccd514e9381fafa51608fcf137253 https://gist.github.com/fgilio/230ccd514e9381fafa51608fcf137253

They've also got quite a few examples on this within their GitHub Docs: 他们在GitHub Docs中也有很多关于此的示例:

https://github.com/axios/axios https://github.com/axios/axios

Interceptor Example: 拦截器示例:

axios.interceptors.response.use((response) => {
    if(response.status === 401) {
         alert("You are not authorized");
    }
    return response;
}, (error) => {
    if (error.response && error.response.data) {
        return Promise.reject(error.response.data);
    }
    return Promise.reject(error.message);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM