skip to Main Content

I can’t for the life of me figure this out, it seems like it should be straight forward but it’s just not clicking.

I have an ES6 app that I created using create-react-app. I’ve got all the templates and layouts set up for the project and came to trying to pull in data from an API that I want to sit inside the app – like a botched MVC where React handles the views and I run the models and controllers in PHP.

So I have a function in one of my components that I want to fetch some data. I use the fetch() function (I know this isn’t yet compatible with a number of browsers but that’s a problem for another day) to fetch a relative path from the component to the model I want to load, however the fetch function treats my path as a call to the base URL followed by the request. So with the site running on localhost:3000, I run the following code in my getData() function…

let test = fetch('../models/overall-stats.php').then(function(response) {
        console.log(response);
        return response;
    });

…the URL that fetch hits is then http://localhost:3000/models/overall-stats.php which simply resolves back to the index.html file and loads the app, rather than the PHP file I’m requesting.

If I need to hit that PHP file to get my data, am I wrong in using fetch? Or am I just using it incorrectly? If I shouldn’t be using fetch what’s a better approach to this problem I’m having?

When I run this on an apache server (after building and deploying) I can get the fetches to work fine (apache recognizes the structure of the URL and hits it as I am expecting) and I hit the file no issues, but I need to be able to work in a local development environment and have the same functionality. The app will end up being deployed live on an apache server.

Any help would be greatly appreciated.

3

Answers


  1. Chosen as BEST ANSWER

    I knew after sleeping on this it would be very straight-forward... I simply had to move my models and controllers into the public directory for them to be accessible. I'll be putting in authentication to the models so that they can't be hit directly, but only through GET requests.


  2. Why don’t you just use something like ${baseUrl}/models/... ?

    Also for solving browsers problem with fetch you can import the Polyfill or simply use axios (my choice)!

    Login or Signup to reply.
  3. Maybe you can try to use ajax to get or post the data from server, just like this:

     $.ajax({
            url: '../models/overall-stats.php',
            data: {
    
            },
            type: 'GET',
            dataType : 'json',
            success : function(res){
               let obj = parseJSON(res)
            }
    
        })
    

    or add this on top in your php file because the CORS :

    header('Access-Control-Allow-Origin: *');  
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search