Vue-cli 3.0 reading JSON with axios

Can someone show me please how to read a file with axios? Reading the docs I get that static assets can reside either in /assets or in /public. So from an action in store.js

I tried

  • in case of /assets: axios.get("../assets/data.json") or axios.get("./assets/data.json") or axios.get("/assets/data.json")

  • in case of /public: axios.get(${process.env.BASE_URL}public/data.json)` or any other more or less meaningful combinations I could imagine (e.g. setting an own Env-variable with the subfolder / setting in file vue.config.js baseUrl to the folder name) - always with the same result:

    404 (not found)

Whatever you put in your /public folder will be available at the root of your app, but without the actual public in the URL. So if your app is at example.com, a foo.json file in /public will be available at example.com/foo.json. Since your app is probably running on the same domain, you can simply call:

axios.get('/foo.json');

But keep in mind that by using axios, you’re making an AJAX request. If your JSON file is a temporary replacement for some real API that will be implemented in the future, this is a good way to simulate the behaviour. But if you actually have some data extracted to JSON files (e.g. app configuration) and you will use them in production, it makes no sense to fetch them asynchronously. You can just directly import it instead:

import myConfig from 'path/to/my/config.json';
2 Likes

I feared it: too stupid to understand the documentation.:flushed: From this point of view, this is exactly what it says in the “public folder” chapter.

Thank’s for your help!