【问题标题】:Axios GET request failed with status code 404Axios GET 请求失败,状态码 404
【发布时间】:2021-04-10 05:22:03
【问题描述】:

我正在尝试构建(使用vue.js)一个博客/文章应用程序,它使用axios 从我的db.json 文件和get request 请求数据。一旦从主要文章列表中单击它,我希望它显示该文章的数据==> 我使用id prop,以便它知道要获取哪篇文章的数据。这里我调用了我的 get 请求(get 请求在另一个文件中,请继续阅读)。

ArticleShow.vue
<script>
import APIService from "@/APIService.js";
export default {
  props: ["id"],    // "id" has been passed as a prop when I import this file to its parent
  data() {
    return {
      article: {}
    };
  },
  created() {
    APIService.getArticle(this.id).then(response => {
      this.article = response.data;
    });
  }
};
</script>

这是我使用的 axios GET 请求(在 APIService.js 文件中)

APIService.js
import axios from "axios";

const apiClient = axios.create({
  baseURL: "http://localhost:5000",
  withCredentials: false,
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json"
  }
});

export default {
  getArticle(id) {
    return apiClient.get("/articles/" + id);
  }
}

我认为这段代码可以工作,但在我的浏览器中出现以下错误:

GET http://localhost:5000/articles/undefined 404 (Not Found)
Uncaught (in promise) Error: Request failed with status code 404
    at createError (createError.js?2d83:16)
    at settle (settle.js?467f:17)
    at XMLHttpRequest.handleLoad (xhr.js?b50d:62)

我尝试捕捉错误,但我无法获得任何有用的信息,说明它来自何处以及如何修复它。我想这可能是导致问题的id prop,但不确定。在ArticleShow 组件的父级中,当在路由器链接中显示ArticleShow 时,我定义了id prop。

ArticleCard.vue
<router-link
      class="article-link"
      :to="{ name: 'ArticleShow', params: { id: article.id } }"
      :article="this.article"
    >

然后又在Articlecard.vue(前一个组件)的父级中

Home.vue
<ArticleCard
      v-for="article in articles"   // I imported *articles* from the vuex store
      :key="article.id"
      :article="article"
      class="ArticleCard"
></ArticleCard>

仍然不确定id prop 是否真的是问题的根源。无论如何,如果您可以解决这个问题,请提供帮助,因为它已经持续了很长时间,非常感谢任何帮助。

【问题讨论】:

  • 是 404 还是连接被拒绝?您的标题和正文不一致,它们是非常不同的错误。
  • 对不起,错误的错误。我现在已经更正了,这是我在浏览器控制台中遇到的错误。我认为 id 道具可能是问题所在,因为在错误消息中它称之为 .../undefined 但我不明白为什么。

标签: javascript json vue.js axios http-status-code-404


【解决方案1】:

错误 404 表示此 URL 不存在:http://localhost:5000/articles/undefined

所以这意味着你没有将任何 id 属性传递给 ArticleShow 组件

【讨论】:

  • 是的,但我遵循了 id 道具的路径,这一切似乎都有意义。不确定错误发生在哪里以及为什么它无法识别 id :(
  • @MattReid 只需尝试 并检查 devtools 网络选项卡,例如
猜你喜欢
  • 2022-11-13
  • 2020-04-05
  • 1970-01-01
  • 2019-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-18
相关资源
最近更新 更多