如何在Vue项目中向本地JSON文件发出axios请求

时间:2019-12-23 13:24:57

标签: vue.js axios

我的Vue JS项目中有一个JSON文件,嵌套在文件夹结构中

src/assets/json/people.json

我正在尝试向App.vue文件中的json资源发出axios请求

export default {
  name: "App",
  data: function() {
    return {
      people: []
    }
  },
  created: function() {
    this.fetchPeople();
  },
  methods: {
    fetchPeople: function() {
      let url = "./src/assets/json/people.json"
      axios.get(url)
      .then(res => {
       this.people = JSON.parse(res);
      })
    }
  }
};

在控制台上,出现以下错误:

Failed to load resource: the server responded with a status of 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:59)

1 个答案:

答案 0 :(得分:2)

你为什么要这么做?

import people from "./src/assets/json/people.json"

可能会做这项工作。

Axios是一个HTTP代理,用于从远程服务器获取数据。 如果文件是本地文件,只需将其导入。