Frank Smith
Frank Smith

Reputation: 23

Local ajax file not being found in reactjs project

I am having a problem with a practise project I am trying to write in Reactjs. This is just a basic react project, I'm not using flux or anything. The project has been set up using create-react-app.

I'm just trying a simple procedure to get some mock data from a local json file (using axios library). The idea eventually is to build a php file that can return data or update a mysql database. The trouble is, that react keeps saying "404 not found" on the local file in question.

Example :

    axios.get('./ajax.json')
            .then(function (result) {
                console.log(result);
            });

All I get is "404 not found" on the ajax.json file. I have tried different ways of referring to it, but all I get is "Not found".

Eventually, I would like the React app to communicate with a php class that I have written via ajax, so that it saves information to a local database. The "ajax.json" file that I am using was just a quick thing for testing purposes. I have tried with a php file as well, but I have the same result.

I am running the app with "npm start" - I'm wondering whether this has something to do with it. I can't find instruction anywhere on how to communicate with local php files using the built in react server (that is used with npm start).

I have managed to make a successful ajax call from the fakejsonplaceholder website, but this is using an http:// call, not a local one.

Is there some kind of special way of doing this with React? What am I missing?

Thanks.

Upvotes: 1

Views: 747

Answers (2)

Frank Smith
Frank Smith

Reputation: 23

I'm not sure whether is a definitive answer, but I just started mucking around in the end, and found success when I put my json file in my "public" folder of my project. Thanks a lot azium I really appreciate your comments.

Upvotes: 1

azium
azium

Reputation: 20614

Your React application is running in your browser, which doesn't have access to your filesystem. If you could fetch files directly from the browser, you would have a major security issue on your hands. You either need to serve your json data from a server, or I would recommend copying the json data into http://myjson.com/ which will give you a url that you can fetch, for testing purposes.

Upvotes: 0

Related Questions