Reputation: 2878
In my Vue project, I have mocked some data for next step development. I already save the test data in a json
file. And my vue project is typical one created with Vue-Cli, and the structure for my project goes as following:
My_project
build
config
data
service_general_info.json
node_modules
src
components
component-A
component-A.vue
as you can see, all the folders are created by the vue-cli originally. And I make a new folder data
and place the test data json file inside.
And I want to read in the data by axios
library in an event handling function inside the component of component-A
as following:
methods: {
addData() {
console.log('add json data...');
axios.get('./../../data/service_general_info.json');
},
},
I use relative path to locate the target file.But get 404 error back. So how to set the path correctly? Currently I am running the dev
mode in local host.
The error message is: GET http://localhost:8080/data/service_general_info.json 404 (Not Found)
Upvotes: 8
Views: 26030
Reputation: 1429
I had this same issue, only the above solutions wouldn't work as it is being uploaded to a subdirectory. I found I needed to put it in the public/assets folder and use:
axios.get(process.env.BASE_URL+'assets/file.json')
While in vue.config.js I have set the local and live paths
module.exports = {
publicPath: process.env.NODE_ENV === 'production'
? '/path/to/app/'
: '/'
}
Upvotes: 2
Reputation: 3209
For me it didn't work using static folder. I had to put it in public folder.
I put json folder in public & then accessed it like below.
getCountries() {
return axios.get('json/country-by-abbreviation.json', { baseURL: window.location.origin })
.then((response) => { return response.data; })
.catch((error) => {
throw error.response.data;
});
}
Upvotes: 5
Reputation: 5604
You can simply read a static JSON file using import. Then assign in data.
import ServiceInfo from './../../data/service_general_info.json';
export default{
data(){
return {
ServiceInfo
}
}
}
Upvotes: -1
Reputation: 1067
If you are doing just for sake of testing then you can save it in public folder and access it directly on http root.
e.g. I have the file results.json in public folder then I can access it using http://localhost:8080/results.json
Upvotes: 6
Reputation: 301
In Vue-cli project, axios
can't get data from custom folder.
You should use static
folder to save test json file.
So you should change axios
call like this:
axios.get('/static/service_general_info.json');
This will get data from json.
Upvotes: 10
Reputation: 387
When the http call is made from the server, axios has no idea that you're on http://localhost:8080, you have to give the full url.
Like this:
methods: {
addData() {
console.log('add json data...');
axios.get('http://localhost:8080/data/service_general_info.json');
},
},
Upvotes: 2