Md Nurul Afsar Pervez
Md Nurul Afsar Pervez

Reputation: 77

How to solve Axios GET request 404 error in Vue?

I want to display questions with related answers. Unfortunately, if I load a single QuestionPage, it is not showing all the answers. This is because I have spotted a logical error in the ./components/Answers.vue component.

I think the problem is in my fetch () function where the endpoint link is undefined (screenshot of the console error https://prnt.sc/198ebdx )

This Answers component is used in QuestionPage, where I think the Question component is not referred correctly to the Answer component.

Upvotes: 0

Views: 423

Answers (1)

Eric Landheer
Eric Landheer

Reputation: 2243

Your <answers :question="question"></answers> in the QuestionPage.vue component should have a v-if="question.id" to prevent loading of the component, in case question defined in your data() function does not exist.

Explanation

The error is thrown in your console, because of an undefined variable used in your HTTP request.

Looking at your Answers.vue component, you have the following code in your created function:

created () {
    this.fetch(`/questions/${this.questionId}/answers`);
},

This question ID refers to your Props / Data structure in the same Answers.vue:

export default {
    props: ['question'],
    mixins: [highlight],
    data () {
        return {
            questionId: this.question.id,
            count: this.question.answers_count,
            answers: [],
            answerIds: [],
            nextUrl: null
        }
    }
}

In your QuestionPage.vue component, you're passing question as a prop to your Answers.vue component. However, this variable is probably undefined. You should check the result of this function first

mounted () {
    this.fetchQuestion ();
    //  alert(this.question)
    //  console.log(this.question)
},

methods: {
    fetchQuestion () {
        axios.get(`/questions/${this.slug}`).then(({data})=> {
          this.question = data.data
        }).catch(error => console.log(error))
    }
}

If that function does not have a result, make sure your slug prop is correct and handled by the back-end.

Upvotes: 1

Related Questions