Vuejs: correct local json file path for axios get request

In my Vue project, I mocked some data to develop the next step. I am already storing the test data in a file json

. And my vue project is typical built with Vue-Cli and the structure for my project is like this:

My_project
    build
    config
    data
        service_general_info.json
    node_modules
    src
        components
            component-A
                component-A.vue

      

as you can see all folders are created by vue-cli natively. And I create a new folder data

and put the test data json file inside.

And I want to read in the library the axios

data in the event handling function inside the component component-A

like this:

  methods: {
    addData() {
      console.log('add json data...');
      axios.get('./../../data/service_general_info.json');
    },
  },

      

I am using a relative path to find the target file. But return a 404 error. So how do you set the path correctly? I am currently running mode dev

on localhost.

Error message: GET http://localhost:8080/data/service_general_info.json 404 (Not Found)

+4


source to share


4 answers


In project Vue-cli axios

cannot get data from user folder.

You must use the static

folder to save the test JSON file.

So you have to change axios

Call like this:



axios.get('/static/service_general_info.json');

      

This will receive data from JSON.

+2


source


If you are testing just for the sake of testing, you can save it in a shared folder and access it directly in the http root.



for example i have a results.json file in a shared folder and i can access it using http: // localhost: 8080 / results.json

+1


source


When the HTTP call is made from the server, axios has no idea that you are at http: // localhost: 8080 , you must give the full URL.

Like this:

methods: {
    addData() {
      console.log('add json data...');
      axios.get('http://localhost:8080/data/service_general_info.json');
    },
  },

      

0


source


You can just read a static JSON file using import. Then assign the data.

import ServiceInfo from './../../data/service_general_info.json';
export default{
    data(){
        return {
            ServiceInfo
        }
    }
}

      

0


source







All Articles