Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vuejs: the correct path of local json file for axios get request

Tags:

json

vue.js

axios

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)

like image 358
Chris Bao Avatar asked Jul 27 '17 09:07

Chris Bao


2 Answers

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.

like image 171
Jin Lin Avatar answered Nov 10 '22 07:11

Jin Lin


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

like image 39
Shankar Gurav Avatar answered Nov 10 '22 08:11

Shankar Gurav