0

I'm using React front end with a PHP back end to communicate with database. I have a login.js page in which I'm sending the state values to a PHP file to communicate and process those logins. When I run the application It's giving me a 404 not found error for the PHP file.

Here is my Login.js

const API = "../../api/dbConnect.php";
<form>
.....
<button type="submit" name="submit" onClick={this.handleSignin}>Sign In</button>
</form>

And the handleSignin function,

handleSignin = (event) => {
        event.preventDefault();

        axios({
            method:'POST',
            url:`${API}`,
            data:this.state,
            headers: { 'content-type': 'application/json' },
        })
        .then(result => {
            console.log(result)
        })
        .catch(error => console.log(error))
    }

The API location is correct as per my folder structure,

root>
    api/dbConnect.php
    public/
    src/components/Login.js

Error is as follows, GET http://localhost:3000/base/api/dbConnect.php 404 (Not Found)

I'm using a basename as base in App.js as <Router basename="/base">.

4
  • Your php file is not served in localhost:3000. You'll need to serve it in a web server, such an Apache and then make requests to it through the web server. Currently you making requests to what seems like the react-app dev server. Commented May 27, 2020 at 6:37
  • I have the entire project folder inside the /var/www/html/react. And I'm making a axios request to PHP page which is under react/api/dbConnect.php. Can you please explain the mistake I'm doing? Commented May 27, 2020 at 6:40
  • 1
    The URL isn't relative to the JS file, it's relative to the URL the browser is currently on (or its explicitly declared base). You shouldn't use relative URLs at all if possible; use '/api/dbConnect.php'. And FWIW, `${API}` is the same as just API. Commented May 27, 2020 at 6:43
  • 1
    This worked! I have changed my API path to http://localhost/react/api/dbConnect.php. Commented May 27, 2020 at 6:45

1 Answer 1

1

I found the mistake. We have to specify the absolute path of the back end file and the file should be served from a http server. In my case it'll something like

const API = "http://localhost/react/api/dbConnect.php";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.