You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS EC2实例中React调用PHP接口出现ERR_CONNECTION_TIMED_OUT问题求助

问题分析:React前端请求PHP后端出现连接超时错误

我用React做前端、PHP做后端开发日历应用,支持用户登录管理日程。AvailableEvents.js负责获取当前用户的关联事件,未登录则返回无权限;AccessEvents.php是后端接口,且确认database.php的数据库连接正常。但React发送请求时出现以下错误:

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

想问代码是否存在问题?如果代码没问题,是不是数据库或访问权限的问题?

相关代码

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']);
}
?>

已尝试的操作

  • 设置了CORS响应头
  • 更换过域名
  • 在AWS EC2实例的http.conf中添加了以下配置:
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Methods "POST, GET, OPTIONS"
    Header set Access-Control-Allow-Headers "Content-Type"
    

想问有没有需要撤销的设置?


问题解答

首先明确:连接超时错误和数据库完全无关,这个错误说明前端根本连不上后端服务器,请求还没到达PHP代码和数据库环节。

代码层面排查

  1. React代码:逻辑无问题,请求方法、Content-Type设置、参数格式都符合要求,错误处理也到位。
  2. PHP代码:CORS头设置、会话校验、数据库查询逻辑都正常。唯一潜在小问题是如果前端传的JSON格式错误,json_decode会返回null,后续取$json_obj['day']会报错,但这不会导致连接超时。

核心排查方向

  • EC2安全组配置:检查是否开放了8000端口的入站规则,允许前端所在IP或所有IP访问。
  • 后端服务状态:确认EC2上的Web服务器(Apache/Nginx)是否在8000端口正常监听,可通过netstat -tulpn命令查看端口占用情况。
  • 服务器可达性:在本地终端执行curl http://ec2...com:8000/backend/AccessEvents.php,测试是否能连通,判断是网络问题还是服务问题。
  • 端口占用冲突:检查8000端口是否被其他进程占用,导致Web服务器无法正常监听。

CORS设置建议

你同时在PHP代码和http.conf中配置了CORS头,会导致响应中出现重复的CORS字段,可能引发浏览器报错(但不是当前连接超时的原因)。建议保留其中一种配置即可,比如保留PHP代码里的CORS设置,删除http.conf中的相关配置,避免冲突。

内容的提问来源于stack exchange,提问作者Cheng Li

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 00:10:31