Trouble getting local JSON data with axios

风流意气都作罢 提交于 2020-07-07 16:19:47

问题


I'm trying to get data from a local json file using axios. Under the console I can't even get a response so I figured I'd ask about it here.

.js file:

var loadData;

function loadData() {
    axios({
        url: "[filepath]/json/docs.json", 
        responseType: 'json',
        credentials: "include",
        mode: "no-cors",
        headers: {
            "Accept": "application/json; odata=verbose"
        }           
    }).then((response) => {
        console.log(response.data);      
    })
}

On the .then((response) line it's telling me I have a syntax error---I think it's pertaining to the response syntax but I'm not so sure. Any thoughts?


回答1:


Use fetch

test() {
    fetch('[filepath]/json/docs.json')
      .then(r => r.json())
      .then(json => {
      })
}

Or put your file in the public folder

axios.get('docs.json') .then(//...)



回答2:


May I know why you need axios for it? You can directly import the json and use it. The function is not even needed actually. If you still want to retain the function, here's a way.

import data from '[filepath]/json/docs.json'

function loadData() {
  return data;
}



回答3:


Simply put your json file in public folder and call it using axios. Suppose if you have json file named called data.json in public folder of your project.

Then call it like

    axios.get('data.json')
    .then(res => console.log(res.data))
    .catch(err => console.log(err)

Before that make sure to import axios. like ,

import axios from 'axios';

Hope it helps.



来源:https://stackoverflow.com/questions/54224164/trouble-getting-local-json-data-with-axios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!