解决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>
在
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)) } }如果该函数没有结果,请确保您的
slugprop是正确的,并由后端处理。