0

I'm a newbie to react. I have created react application using npx create-react-app. In actions,axios.get is throwing localhost:3000 file not found error. Below is the code which is in src/actions/index.js

       export function lang(language) {
      let url = "./../resources/strings/strings_" + language + ".json";
      return dispatch => {
        axios.get(url).then(response => {
          console.log(response.data)
        }).catch(response => {
          console.log(response);
        });
      }
    }

This is the project structure [1]: https://i.sstatic.net/CwTJg.png

What am I doing wrong? I couldn't find a proper solution for this. Thanks in advance.

2

1 Answer 1

3

I agree with Easwar, you need to look at the answer to that question.

It appears axios only operates in the /public folder so you would need your json files in the public folder. You could put them within a folder in the public folder if you wanted.

This makes sense because the webpack bundle is in the public folder and once the app is bundled only files within the public folder are available to your react project.

Since axios is an xhr request library at the moment you use it the only file structure it can possibly see is in the public folder so most likely: index.html, manifest.json, and your webpack bundle.js which has all your js code bundled into 1 file.

Sign up to request clarification or add additional context in comments.

7 Comments

Is there a way i can achieve this by keeping json file in src folder? @ekr990011
Only if you use instead an import or require not axios. Since you are in react and most likely es6 if you used create-react-app, import "[file-path-here]". Axios can't because it happens at the event you use it at. Is there a reason you want to use axios to get at those json files? The answer to this question talks about importing json files: stackoverflow.com/questions/39686035/import-json-file-in-react
Axios is really for fetching data from a server. If you didn't want your end user to download those json files until requested you really need a web server separate from your react front end to house that json data then you can request that data from the server with axios.
I need to import json files dynamically based on language chosen. How can I do it? import langaugePath from './../resources/strings/strings_" + language + ".json' . Here language should be replaced by localStorage value
Well your language variable could be from your state for example. I assume the end user gets to choose their language, which means you most likely have it in state somewhere or as a prop passed down to this component that is going to serve up the language json.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.