Nuxt.js: How to get data from local json file using actions and axios.get()?

Created on 1 Nov 2017  路  4Comments  路  Source: nuxt/nuxt.js

I wrote Action, that should get data from db.json file. But I get: "xhr.js:178 GET http://localhost:8083/data/db.json 404 (Not Found)".
Why is it, if my path is correct (db.json is in the same folder)?
In profileActions.js:

import axios from "axios";
var customData = require('./db.json');

export function fetchUsers(){
    return function(dispatch){
        axios.get('./db.json')
            .then((response) => {
                dispatch({type:'FETCH_USERS_FULFILLED', payload:response.data});
            })
            .catch((err) => {
                dispatch({type:'FETCH_USERS_REJECTED', payload:err});
            })
    }
}

This question is available on Nuxt.js community (#c1782)

Most helpful comment

If anyone ends up here, I found a solution if you are using create-react-app.
Got it working by throwing my db.json file into the Public folder and calling it by:
axios.get('db.json') .then(//...)

All 4 comments

An HTTP request cannot use relative path as you file structure, is's relative to you baseURL or domain.

const ax = axios.create({
  baseURL: 'http://localhost:3000/data'
})
ax.get('db.json')

//or 

 axios.get('/data/db.json')

BTW, highly recommend you to use axios-module which has good integration with Nuxt.

You could also use the fetch API:

  created: function() {
    fetch('data/db.json')
      .then(r => r.json())
      .then(json => {
        this.db = json
      })

// and then  access this.db which is now serialized


If anyone ends up here, I found a solution if you are using create-react-app.
Got it working by throwing my db.json file into the Public folder and calling it by:
axios.get('db.json') .then(//...)

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mattdharmon picture mattdharmon  路  3Comments

vadimsg picture vadimsg  路  3Comments

surmon-china picture surmon-china  路  3Comments

vadimsg picture vadimsg  路  3Comments

vadimsg picture vadimsg  路  3Comments