Home > OS >  Adding http response code in php breaks axios
Adding http response code in php breaks axios

Time:10-10

After adding http response code in the login file axios is returning these errors even if the login email and password are correct and the catch block isn't executed I get these errors. If I remove the http_response_code(400) it will work and return the user or the message with 200 ok but I don't want that.

How do i fix it? thanks in advance.

Access to XMLHttpRequest at 'http://localhost/classroom-api/api/user/login.php' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

POST http://localhost/classroom-api/api/user/login.php net::ERR_FAILED

login.php

    <?php 
  // Headers
  header('Access-Control-Allow-Origin: *');
  header('Content-Type: application/json');
  header('Access-Control-Allow-Methods: POST');
  header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');

  require_once '../../vendor/autoload.php';
  use Firebase\JWT\JWT;
  require_once '../../config/Database.php';
  require_once '../../models/User.php';

  // Connect db
  $database = new Database();
  $db = $database->connect();

  $user = new User($db);

  try {
    // Get posted data
    $data = json_decode(file_get_contents("php://input"));

    if(empty($data->email) || empty($data->password)) {
      throw new Exception("Please enter all fields");
    }

    $user->email = $data->email;
    $user->password = $data->password;
    
    if ($user->login()) {
      // Create token
      $key = 'ajdZiWodDaAs1123';
      $iat = time();
      $payload = [
        'iss' => 'localhost',
        'aud' => 'localhost',
        'iat' => $iat,
        'nbf' => $iat,
        'exp' => $iat   259200000, // 3 days
        'data' => [
          "id" => $user->id
        ]
      ];
      $token = JWT::encode($payload, $key, 'HS256');

      echo json_encode(
        array(
          "id" => $user->id,
          "full_name" => $user->fname ." ".$user->lname,
          "email" => $user->email,
          "token" => $token
        )
      );
    } else {
      throw new Exception("Invalid credentials");
    }
    
  } catch (Exception $e) {
    http_response_code(400);
    echo json_encode(
      array('message' => $e->getMessage())
    );
  }
?>

axios

import axios from 'axios';

const base_url = 'http://localhost/classroom-api';
const route = '/api/user';

export const login = async (userData) => {
  const res = await axios.post(base_url   route   '/login.php', userData);
  console.log(res);
};

although it does work in postman

enter image description here

enter image description here

CodePudding user response:

Browsers will first send an OPTIONS request to check for CORS headers.

Add this right after the headers:

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS')
    exit('ok');
  • Related