Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I wrote Action, should get data from db.json file. But

Error: message "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});
            })
    }
}
like image 448
Jurate Avatar asked Nov 01 '17 21:11

Jurate


People also ask

Can I use Axios with local JSON file?

Axios cannot read from the file system. It can only make HTTP calls. If you are running in a node environment, look into the fs package, this will let you read from the local file system. Otherwise you will need to expose the json file via a webserver to make it accessible to Axios.

How use Axios get method?

A GET request can be made with Axios to “get” data from a server. The HTTP get request is performed by calling axios. get() . The get() method requires two parameters to be supplied to it.

Does Axios convert JSON to object?

Axios automatically transforms the data returned from the server, but with fetch() you have to call the response. json method to parse the data to a JavaScript object.


2 Answers

I meet the similar problem before.I create my react app by create-react-app command.And find that you can only get the static file from the public folder.If you want to the get "db.json",you should put the "db.json" into the public folder.

like image 171
Thomas.lin Avatar answered Sep 25 '22 17:09

Thomas.lin


I know that this question is answered long back. It will help people like me. Instead of using axios or other network libraries you can directly import the json file like below and return it in dispatcher. If you are using local json to test it why do you need network libraries.

import data from './response.json'

export function initializeApp() {
  return function (dispatch) {
    dispatch({
      type: ActionTypes.ActionName,
      payload: data
    });

  }
}
like image 35
PremPalanisamy Avatar answered Sep 24 '22 17:09

PremPalanisamy