Trouble getting local JSON data with axios

Viewed 27857

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?

3 Answers

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.

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

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(//...)
Related