Im creating a very basic login page and i'm trying to use php to verify the user login. Here is the code I'm using to access the php file.
axios.post("login.php", {
user: 'Fred',
pass: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
The PHP file is located within the src folder of the react app.
── src
│ ├── components
│ │ ├── BrowsePage
│ │ │ ├── BrowsePage.css
│ │ │ ├── BrowsePage.js
│ │ │ └── default.jpg
│ │ ├── CreatePage
│ │ │ ├── CreatePage.css
│ │ │ └── CreatePage.js
│ │ ├── Header
│ │ │ ├── Header.css
│ │ │ └── Header.js
│ │ ├── LoginPage
│ │ │ ├── LoginPage.css
│ │ │ ├── LoginPage.js
│ │ │ └── logo.svg
│ │ ├── ProfilePage
│ │ │ ├── ProfilePage.css
│ │ │ └── ProfilePage.js
│ │ └── RecPage
│ │ ├── default.jpg
│ │ ├── RecPage.css
│ │ └── RecPage.js
│ ├── index.css
│ ├── index.js
│ ├── login.php
│ └── registerServiceWorker.js
When I make the call it logs
xhr.js:178 POST http://localhost:3000/login.php 404 (Not Found)
The current path to the php document does not work, and none of the others I've tried work. What is the path to make an axios call to this php document?
You'll need to setup a server locally that your React application can proxy certain http requests to. This server will run your login.php script and authenticate the username/password. create-react-app
looks for a proxy
value in your package.json and tells webpack-dev-server
to forward any calls to api/foobar
to wherever you have declared that your back-end will be running.
In your package.json add:
"proxy": "http://localhost:8000"
This tells React to forward requests made to http://localhost:3000/api/login
to http://localhost:8000/api/login
Then modify your axios call to look like this
axios.post("/api/login", ..., ...).then()
Next, you have to get your PHP server running on http://localhost:8000
and set up your server application to handle POST requests made to /api/login
.
I'm not a PHP guy but I've heard Laravel is nice to work with. It would be easier if your PHP backend was in its own directory completely.