I am working on a project where my React frontend sends a POST request to a PHP backend using Axios. However, on the server-side, $_SERVER[‘REQUEST_METHOD’] consistently indicates that the request is a GET, even though I am using the POST method in Axios.
Front-end with react
const handle_submit = async (event) => {
event.preventDefault();
try {
const axios_response = await axios.post(
'http://localhost/deletable/tutorial/vite-project/php_backend/index.php',
{ firstname, lastname, email, password, enrollment_year, dob, is_note_sharer },
{ headers: { 'Content-Type': 'application/json' } }
);
console.log('axios_response', axios_response);
} catch (error) {
console.error('Error submitting data', error);
}
};
PHP Backend
header('Access-Control-Allow-Origin: http://localhost:5173');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Credentials: true');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$data = json_decode(file_get_contents('php://input'));
echo json_encode(['status' => 'success', 'data' => $data]);
} else {
echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
}
Issue:
Despite using POST in the Axios request, $_SERVER[‘REQUEST_METHOD’] in PHP evaluates to GET. I have also tried adding Access-Control-Allow-Methods: POST in the PHP headers, but the issue persists.
Additional Info:
The frontend is running on http://localhost:5173.
The backend is served from http://localhost.
CORS headers have been added to the PHP file.
No network errors are observed in the browser’s developer tools.
Question:
What could be causing the PHP backend to treat the POST request as a GET, and how can I resolve this issue?