在 xampp 中向 REST API 发出请求时出现问题

问题描述 投票:0回答:1

我在连接计算机上的前端和后端时遇到问题。我在 VSC 中使用 LiveServer 来服务前端,以避免在加载图像和模块时出现 CORS 问题。对于后端,我使用 Xampp 并将文件放在服务器文件夹中。问题是当我发送数据时,它返回一个空文件。

来自 login.js 的请求:

$(document).ready(function() {
    $('#login-form').submit(function(event) {
      event.preventDefault(); 
      const username = $('#email').val();
      const password = $('#password').val();
      // Realizar una solicitud AJAX para iniciar sesión
      $.ajax({
        url: 'http://localhost/web/back/public/login',
        method: 'POST',
        dataType: 'json',
        contentType: 'application/json',
          console.error(error);
        }
      });
    });
  });

服务器上的Index.php文件:

<?php
include('../app/routes/Login.php');
foreach ($routes as $url => $route) {
  $method = $route[0];
  $controller = $route[1];
  $action = $route[2];

  error_log("Procesando ruta: $url");
  error_log("Método de la solicitud: " . $_SERVER['REQUEST_METHOD']);
  error_log("URI de la solicitud: " . $_SERVER['REQUEST_URI']);

  if ($_SERVER['REQUEST_METHOD'] === $method && preg_match('#^'.$url.'$#', $_SERVER['REQUEST_URI'])) {
    error_log("Coincidencia encontrada, llamando al controlador: $controller y a la acción: $action");

    $controller = new $controller();
    $controller->$action();
    break;
  }
}
?>

服务器上的Login.php文件:

<?php
use back\app\controllers\LoginController;

$routes = [
  '/login' => ['POST', LoginController::class, 'login'],
  '/logout' => ['POST', LoginController::class, 'logout']
];
?>

服务器上的LoginController.php文件:

<?php
session_start(); 
require_once '../../tools/connection.php';

$this->hola();
class LoginController
{

    function hola(){
        echo("HOLA");
    }
    public function login()
    {
        $data = json_decode(file_get_contents('php://input'), true);
        $username = $data['username'];
        $password = $data['password'];

        if ($this->authenticate($username, $password)) {
            session_start();
            $_SESSION['logged_in'] = true;
            $_SESSION['username'] = $username;

            $response = [
                'success' => true,
                'message' => 'Inicio de sesión exitoso'
            ];
            header('Content-Type: application/json');
            echo json_encode($response);
        } else {
            $response = [
                'success' => false,
                'message' => 'Nombre de usuario o contraseña incorrectos'
            ];
            header('Content-Type: application/json');
            http_response_code(401);
            echo json_encode($response);
        }
    }

    public function logout()
    {
        // Cierra sesión
        session_start();
        session_destroy();

        $response = [
            'success' => true,
            'message' => 'Cierre de sesión exitoso'
        ];
        header('Content-Type: application/json');
        echo json_encode($response);
    }
   
    private function authenticate(string $username, string $password)
    {
        if (empty($username) || empty($password)) {
            return ['error' => 'Usuario o contraseña vacíos', 'code' => 401];
        }

        $conn = connect();

        $sql = "SELECT p.*, CASE 
                WHEN a.IdPersona IS NOT NULL THEN 'Administrador' 
                WHEN t.IdPersona IS NOT NULL THEN 'Tutor' 
                WHEN al.IdPersona IS NOT NULL THEN 'Alumno' 
                ELSE NULL 
            END AS Rol
            FROM Persona p
            LEFT JOIN Administrador a ON a.IdPersona = p.IdPersona
            LEFT JOIN Tutor t ON t.IdPersona = p.IdPersona
            LEFT JOIN Alumno al ON al.IdPersona = p.IdPersona
            WHERE p.CorreoElectronico = :username";

        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':username', $username);

        $stmt->execute();

        $result = $stmt->fetch();

        if (!$result || $result['Password'] !== $password) {
            return ['error' => 'Usuario o contraseña incorrectos', 'code' => 401];
        }

        switch ($result['Rol']) {
            case 'Administrador':
                $userType = 'administrador';
                break;
            case 'Tutor':
                $userType = 'tutor';
                break;
            case 'Alumno':
                $userType = 'alumno';
                break;
            default:
                return ['error' => 'Tipo de usuario inexistente', 'code' => 401];
        }

        return [
            'id' => $result['IdPersona'],
            'nombre' => $result['Nombre'],
            'apellido' => $result['Apellido'],
            'email' => $result['CorreoElectronico'],
            'rol' => $userType
        ];
    }
}

在这个文件中,我添加了一个“hello”函数来检查是否正在访问 LoginController,但它似乎没有到达那个文件。

浏览器控制台出错

预检:

xhr:

谢谢!

php apache rest server xampp
1个回答
0
投票

问题是htaccess文件不允许使用CORS,但是用下面的代码修改后就可以了:

Header 设置 Access-Control-Allow-Origin %{HTTP_ORIGIN}e env=HTTP_ORIGIN 标头设置 Access-Control-Allow-Credentials true 标头集 Access-Control-Allow-Headers "Content-Type, Authorization" 标头集 Access-Control-Allow-Methods“GET、POST、PUT、DELETE、OPTIONS” 标头集 Access-Control-Allow-Headers “Content-Type”

重写引擎开启 重写基础 / RewriteCond %{REQUEST_FILENAME} !-f 重写规则 ^ /web/back/public/index.php [QSA,L]

© www.soinside.com 2019 - 2024. All rights reserved.