AWS ec2 instance: React fetch data from PHP, getting error: ERR_CONNECTION_TIMED_OUT

22 views Asked by At

I use React for frontend and PHP for backend, and I am making a calendar where users can login and manage their events. Currently, the availableEvents.js is intended to access all events associated with the current user; if the user is not logged in, it would return that the user does not have access to the content. The AccessEvents.php is the backend stuff, and I assume the database.php used to access MySQL database is correct. But my React sends a request to backend, it says that

AvailableEvents.js:11 
 POST http://ec2...com:8000/backend/AccessEvents.php net::ERR_CONNECTION_TIMED_OUT

Can anyone help if there is any issue in the code? If there is no, then is it the problem of database? probably the access to database?

// AvailableEvents.js
useEffect(() => {
    const fetchEvents = async () => {
      try {
        const response = await fetch('http://ec2...com:8000/backend/AccessEvents.php', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            day: currentDate.getDate(),
            month: currentDate.getMonth() + 1, // Month is zero-based, so we add 1
            year: currentDate.getFullYear(),
          }),
        });
        const data = await response.json();
        setEventList(data.events); // the server responds with an array of events
      } catch (error) {
        console.error('Error fetching events:', error);
      }
    };

    fetchEvents();
  }, [currentDate]); // Trigger fetchEvents when currentDate changes

// AccessEvents.php
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
session_start();
require 'database.php';
if (isset($_SESSION["username"]) && isset($_SESSION["id"])){
    // if the user is logged in
    // provide buttons that enable the user to perform different actions
    $user = $_SESSION['username'];
    $userID = $_SESSION['id'];
    $json_str = file_get_contents('php://input');
    //This will store the data into an associative array
    $json_obj = json_decode($json_str, true);
    $day = $json_obj['day'];
    $month = $json_obj['month'];
    $year = $json_obj['year'];
    $stmt = $mysqli->prepare("SELECT * FROM calendar WHERE creator = ? AND day = ? AND month = ? AND year = ?");
    $stmt->bind_param("iiii", $userID, $day, $month, $year);
    $stmt->execute();
    $result = $stmt->get_result();
    // access all the events by executing 
    $events = array();
    while ($row = $result->fetch_assoc()) {
        $events[] = $row;
    }

    // Return JSON response with the fetched events
    header('Content-Type: application/json');
    echo json_encode(['events' => $events]);
} else {
    // Handle unauthorized access or other errors
    http_response_code(401); // Unauthorized
    echo json_encode(['error' => 'Unauthorized']);
}
?>

I have tried setting headers, using different domains, and Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Methods "POST, GET, OPTIONS" Header set Access-Control-Allow-Headers "Content-Type" in the http.conf in the aws ec2 instance. If there is anything that I should undone, please let me know.

0

There are 0 answers