首頁  >  問答  >  主體

解決Vue中Axios GET請求404錯誤的方法是什麼?

<p>我想顯示與相關答案的問題。不幸的是,如果我加載一個單獨的<code>QuestionPage</code>,它不會顯示所有的答案。這是因為我在<code>./components/Answers.vue</code>元件中發現了一個邏輯錯誤。 </p> <p>我認為問題出在我的<code>fetch()</code>函數中,其中的端點連結未定義(控制台錯誤的截圖https://prnt.sc/198ebdx)< /p> <p>這個Answers元件在QuestionPage中使用,我認為<code>Question</code>元件沒有正確引用<code>Answer</code>元件。 </p>
P粉738046172P粉738046172416 天前562

全部回覆(1)我來回復

  • P粉191610580

    P粉1916105802023-08-30 11:13:35

    QuestionPage.vue元件中,您的<answers :question="question"></answers>應該有一個v-if= "question.id"來防止載入元件,以防data()函數中定義的question不存在。

    解釋

    控制台中報錯是因為在您的HTTP請求中使用了一個未定義的變數。

    查看您的Answers.vue元件,在created函數中有以下程式碼:

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

    這個問題ID是指同一個Answers.vue中的Props / Data結構:

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

    在您的QuestionPage.vue元件中,您將question作為prop傳遞給Answers.vue元件。然而,這個變數可能是未定義的。您應該先檢查這個函數的結果

    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))
        }
    }

    如果函數沒有結果,請確保您的slug prop是正確的,並由後端處理。

    回覆
    0
  • 取消回覆