在php中添加http响应代码会破坏axios

ql3eal8s  于 2022-11-05  发布在  iOS
关注(0)|答案(1)|浏览(130)

在登录文件中添加http响应代码后,即使登录电子邮件和密码正确,并且catch块没有执行,axios也会返回这些错误。如果我删除http_response_code(400),它会工作,并返回用户或消息200 ok,但我不希望这样。
我该怎么修呢?先谢谢了。
CORS策略已阻止从源'http://localhost:3000'访问位于'http://localhost/classroom-api/api/user/login.php'的XMLHttpRequest:对预检请求的响应未通过访问控制检查:它不具有HTTP ok状态。
请登录后查看以下网址:
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);
};

尽管它在postman中确实有效

ecbunoof

ecbunoof1#

浏览器将首先发送OPTIONS请求以检查CORS标头。
在标题后面添加以下内容:

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

相关问题