404 Not Found

  {
    path: '/404',
    name : 'NotFound404',
    component : NotFound404
  },
    {
    path:'*',
    redirect : '/404'
  }

views에 NotFound404.vue를 만들고, router/index.js에 route를 등록했다.

path : '*' 일 떄 redirect '/404'는 기존에 명시한 경로가 아닌 모든 경로일 때는 404 page로 redirect하게 하는 것이다.

이 때 routes의 최하단부에 작성해야 한다.

 

 

 

주소 입력해서 직접 화면을 확인했다.

없는 주소를 입력해도 404 페이지로 이동한다.

 

 

 

형식은 유효하지만 특정 리소스를 찾을 수 없는 경우

예를 들어, django에 articles/1/로 요청했지만 1번게시글이 삭제된 상태이다. 이때 path : '*'를 만나 404page가 렌더링되지 않고 기존에 명시한 articles/:id/에 대한 component가 렌더링된다.

하지만 데이터가 존재하지 않기 때문에 정상적으로 렌더링되지않는다.

데이터가 없음을 명시하고 404 페이지로 이동해야 한다.

 

 

Dog API 문서 (https://dog.ceo/dog-api/)를 참고하여 동적인자로 강아지 품종을 전달해 품종에 대한 랜덤이미지를 출력하는 페이지를 만든다.

 

 

npm i axios

axios 설치

 

 

<template>
  <div></div>
</template>

<script>
export default {
    name : 'DogView'
}
</script>

<style>

</style>

views/DogView.vue 작성

 

 

  {
    path: 'dog/:breed',
    name : 'dog',
    component : DogView
  },

router/index.js에 routes 등록 ( '*'보다 상단에 등록해야 한다.)

 

 

 

 

<template>
  <div>
    <img :src="imgSrc" alt="">
  </div>
</template>

<script>
import axios from 'axios'
export default {
    name : 'DogView',
    data(){
        return {
            imgSrc : null,
        }
    },
    methods : {
        getDogImage(){
            const breed = this.$route.params.breed
            const dogImageSearchURL = `https://dog.ceo/api/breed/${breed}/images/random`
        axios({
            method : 'get',
            url : dogImageSearchURL
        })
        .then((response)=>{
            console.log(response)
        })
        .catch((error)=>
            console.log(error))
        }
    },
    created(){
        this.getDogImage()
    }
}
</script>

DogView.vue

Dog api 문서를 참고하여 axios 로직 작성

 

 

 

 

dog/husky로 주소를 입력했을 때, 이미지 링크가 response.message에 있는 것을 확인했다.

 

 

 

        .then((response)=>{
            this.imgSrc = response.data.message
        })

imgSrc 변수에 대입하도록 한다.

 

 

정상 동작한다.

 

 

<template>
  <div>
    <p v-if="!imgSrc">{{message}}</p>
    <img v-if="imgSrc" :src="imgSrc" alt="">
  </div>
</template>
    data(){
        return {
            imgSrc : null,
            message : '로딩중'
        }
    },

 

axios 요청이 오는 중 동작하고 있음을 표현하기 위한 로딩 메세지를 정의한다.

로딩중 글자가 뜨다가 강아지 사진이 생기면 글자대신 사진이 나타난다.

 

 

 

        .catch((error)=>{
            this.message = `${this.$route.params.breed}는 없는 품종입니다`
            console.log(error)
        })

axios 요청이 실패할 경우 자료가 없음을 표현한다.

 

 

 

 

 

        .catch((error)=>{
            this.$router.push('/404')
            console.log(error)
        })

 

axios 요청이 실패할 경우 404페이지로 이동시킬수도 있다.