What is the way to solve Axios GET request 404 error in Vue?
P粉738046172
P粉738046172 2023-08-30 00:23:34
0
1
588
<p>I want to display questions with related answers. Unfortunately, if I load a separate <code>QuestionPage</code>, it does not show all the answers. This is because I found a logic error in the <code>./components/Answers.vue</code> component. </p> <p>I think the problem is in my <code>fetch()</code> function, where the endpoint link is undefined (screenshot of console error https://prnt.sc/198ebdx)< /p> <p>This Answers component is used in QuestionPage. I think the <code>Question</code> component does not reference the <code>Answer</code> component correctly. </p>
P粉738046172
P粉738046172

reply all(1)
P粉191610580

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

explain

The error reported in the console is because an undefined variable was used in your HTTP request.

View your Answers.vue component, there is the following code in the created function:

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

This question ID refers to the 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 pass question as prop to the Answers.vue component. However, this variable may be undefined. You should first check the result of this function

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 the function has no results, make sure your slug prop is correct and handled by the backend.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template