Trouble getting local JSON data with axios
22,531
Solution 1
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.
Solution 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;
}
Solution 3
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(//...)
Author by
Bodrov
Updated on December 13, 2020Comments
-
Bodrov over 3 years
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?-
joelnet over 5 yearsAxios cannot read from the file system. It can only make HTTP calls. If you are running in a node environment, look into the
fs
package, this will let you read from the local file system. Otherwise you will need to expose the json file via a webserver to make it accessible to Axios. -
Derek Pollard over 5 yearsYou seem to be trying to use a configuration known to
fetch
inaxios
. Axios doesn't have a lot of those config params
-
-
Bodrov over 5 yearsThe original data is XML and came from a url. Since the data I'm using now is for testing purposes it's in JSON and is a local file.