Search code examples
phpreactjsexpresscreate-react-app

create-react-app and loading image dynamically via php file


I'm migrating an react/php project (It was run on apache) to create-react-app and so Express.js/live reloading etc (for development).

In this project there are images uploaded from users and they are save outside the document root via php file that accepts as querystring the name of file to load.

file.php?image=file_name.png

and its relative react's component is

const Img = (props) => {

    const findFile = () => {
        // base64
        if(props.file && props.file.startsWith('data:image/')){
            return props.file;
        }

        return "file.php?name=" + props.file + "&type=" + props.type;
    };

    return (
        <img src={findFile()} alt={props.alt || props.file}/>
    );

};

After migrating to create-react-app, I added a proxy in package.json

"proxy":"http://localhost"

but in this way, the images are loaded only when the user is on dashboard page. In the other pages, the images don't works because change the path of file.php.

In dashboard (http:/localhost/auth)

127.0.0.1 - - [10/Oct/2017:23:59:12 +0200] "GET /file.php?name=avatar4.png&type=avatarDefaultDir HTTP/1.1" 200 12295

In an other page (eg: http://localhost/auth/profile)

127.0.0.1 - - [10/Oct/2017:23:59:17 +0200] "GET /auth/file.php?name=avatar4.png&type=avatarDefaultDir HTTP/1.1" 200 27

How I could to resolve this issue?


Solution

  • You need to use the correct path to the file.php file and use absolute path to the file.php

    instead of

    return "file.php?name=" + props.file + "&type=" + props.type;
    

    use

    return "/file.php?name=" + props.file + "&type=" + props.type;
    

    this is assuming file.php is in the root of your project