ANIMEXD 0 Newbie Poster

i am making api in PHP but i have some problems with cors(preflight) i know how the cors works, my problem is when i request the data from api with (fetch api) i get the response from the server(api) but it suppose to also send cookie for authentication purposes but i can't see any cookies on the browser(chrome) i dont know why?

Here the code for authentication :

<?php

if (isset($_SERVER["HTTP_ORIGIN"]) === true) {
    $origin = $_SERVER["HTTP_ORIGIN"];
    $allowed_origins = array(
        "http://domain"
    );
    if (in_array($origin, $allowed_origins, true) === true) {
        header('Access-Control-Allow-Origin: ' . $origin);
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods: POST');
        header('Access-Control-Allow-Headers: Content-Type');
    }
    if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
        exit; // OPTIONS request wants only the policy, we can stop here
    }
}

// include bootstraper
require_once "../../index.php";

// instantiate admin model
$admin_model = new Admin();
$admin_data = $admin_model->read_admin()[0];

// get request raw data from client (user)
$raw_data = json_decode(file_get_contents("php://input"), true);

// success can login
if ($raw_data["username"] == $admin_data["username"]
    && $raw_data["password"] == $admin_data["password"]) {

    // create token
    $new_token = JWT::sign([
        "algo" => "sha256",
        "typ" => "jwt",
    ], [
        "admin" => true,
        "iat" => date("Y-m-d H:i:s"),
        "exp" => date("Y-m-d H:i:s", strtotime("+1 minutes", strtotime(date("Y-m-d H:i:s")))),
    ], SECRET);

    // generate new token
    setcookie("token", $new_token, time() + 60, "/");
    echo json_encode(["message" => "New token generated!", "data" => [], "logged" => true]);
    http_response_code(200);
    exit();

} else { // invalide inputs

    // send error respons
    echo json_encode(["message" => "Error!", "data" => [], "logged" => false]);
    http_response_code(400);
}

Thanks in advance :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.