-2

I am getting cors error on calling login api from react js.

https://i.stack.imgur.com/9qRNt.png

API's are build in core php.

I tried many options after searching google but these errors comes continue in inspect element and no response is coming...

PHP API CODE

<?php
include_once './config/database.php';
require "./vendor/autoload.php";
use \Firebase\JWT\JWT;

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Max-Age: 360000");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
header("content-type: application/json");



$databaseService = new DatabaseService();
$conn = $databaseService->getConnection();

$secret_key = "aaaaa123";
$issuer_claim = ""; // this can be the servername
$audience_claim = "";


$data = json_decode(file_get_contents("php://input"));
$action = isset($data->action) ? $data->action : "";
if($action=="register")
{
    $name = $data->name;
    $email = $data->email;
    $password = $data->password;

    $table_name = 'users';

    $query = "INSERT INTO " . $table_name . "
                    SET name = :name,
                        email = :email,
                        password = :password";

    $stmt = $conn->prepare($query);

    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':email', $email);
    $password_hash = password_hash($password, PASSWORD_BCRYPT);
    $stmt->bindParam(':password', $password_hash);

    if($stmt->execute()){

        http_response_code(200);
        echo json_encode(array("success"=>true,"message" => "User was successfully registered."));
    }
    else{
        http_response_code(400);

        echo json_encode(array("success"=>false, "message" => "Unable to register the user."));
    }

}
elseif($action=="login")
{
    $email = $data->email;
    $password = $data->password;

    $table_name = 'users';

    $query = "SELECT id, name, password FROM " . $table_name . " WHERE email = ? LIMIT 0,1";

    $stmt = $conn->prepare( $query );
    $stmt->bindParam(1, $email);
    $stmt->execute();
    $num = $stmt->rowCount();
    // echo "number: " . $num; die;
    if($num > 0){
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $id = $row['id'];
        $name = $row['name'];
        $password2 = $row['password'];

        if(password_verify($password, $password2))
        {
           
            $issuedat_claim = time(); // issued at
            $notbefore_claim = $issuedat_claim + 10; //not before in seconds
            $expire_claim = $issuedat_claim + 36000; // expire time in seconds
            $token = array(
                "iss" => $issuer_claim,
                "aud" => $audience_claim,
                "iat" => $issuedat_claim,
                "nbf" => $notbefore_claim,
                "exp" => $expire_claim,
                "data" => array(
                    "id" => $id,
                    "name" => $name,
                    "email" => $email
            ));

         
            http_response_code(200);

            $jwt = JWT::encode($token, $secret_key);
            echo json_encode(
                array(
                    "success"=>true,
                    "message" => "Successful login.",
                    "jwt" => $jwt,
                    "email" => $email,
                    "expireAt" => $expire_claim
                ));
        }
        else{

            http_response_code(401);
            echo json_encode(array("success"=>false, "message" => "Login failed.", "password" => $password));
        }
    }
}
elseif($action=="add_share")
{
    $headers = apache_request_headers();
    // echo $headers['X_REQUESTED_WITH'];
    // echo json_encode( );  
    $authHeader = $headers['Authorization'];
    $checkAuth = checkAuth($authHeader, $secret_key);

    $ar = json_decode($checkAuth, true);
    // print_r($ar);
    if($ar['error']=="")
    {
        $userID = $ar["decoded"]['data']['id'];
        $user_id = $userID;
        $share_name = $data->share_name;
        $purchase_amount = $data->purchase_amount;
        $qty = $data->qty;
        $provider = $data->provider;

        $table_name = 'share';

        $query = "INSERT INTO " . $table_name . "
                        SET user_id = :user_id,
                            share_name = :share_name,
                            purchase_amount = :purchase_amount,
                            provider = :provider,
                            qty = :qty";

        $stmt = $conn->prepare($query);

        $stmt->bindParam(':user_id', $user_id);
        $stmt->bindParam(':share_name', $share_name);
        $stmt->bindParam(':purchase_amount', $purchase_amount);
        $stmt->bindParam(':provider', $provider);
        $stmt->bindParam(':qty', $qty);

        if($stmt->execute()){

            http_response_code(200);
            echo json_encode(array("success"=>true,"message" => "Share Added Successfully."));
        }
        else{
            http_response_code(400);

            echo json_encode(array("success"=>false,"message" => "Unable to add share."));
        }

    }
    else
    {
        echo $checkAuth;
    }
}
elseif($action=="get_all_share")
{
    $headers = apache_request_headers();
    // echo $headers['X_REQUESTED_WITH'];
    // echo json_encode( );  
    $authHeader = $headers['Authorization'];
    $checkAuth = checkAuth($authHeader, $secret_key);

    $ar = json_decode($checkAuth, true);
     // print_r($ar);
    if($ar['error']=="")
    {
        $userID = $ar["decoded"]['data']['id'];
        $table_name = 'share';

        $query = "SELECT * FROM " . $table_name . " WHERE user_id = ?";

        $stmt = $conn->prepare( $query );
        $stmt->bindParam(1, $userID);
        $stmt->execute();

        $row = $stmt->fetchAll(PDO::FETCH_ASSOC);

        http_response_code(200);
        echo json_encode(array("success"=>true,"message" => "Share list.", "list"=>$row));
        
    }
    else
    {
        echo $checkAuth;
    }
}
elseif($action=="update_share")
{
    $headers = apache_request_headers();
    // echo $headers['X_REQUESTED_WITH'];
    // echo json_encode( );  
    $authHeader = $headers['Authorization'];
    $checkAuth = checkAuth($authHeader, $secret_key);

    $ar = json_decode($checkAuth, true);
    // print_r($ar);
    if($ar['error']=="")
    {
        $userID = $ar["decoded"]['data']['id'];
        $user_id = $userID;
        $id = $data->id;
        $share_name = $data->share_name;
        $purchase_amount = $data->purchase_amount;
        $qty = $data->qty;
        $provider = $data->provider;

        $table_name = 'share';

        $query = "UPDATE " . $table_name . "
                        SET user_id = :user_id,
                            share_name = :share_name,
                            purchase_amount = :purchase_amount,
                            provider = :provider,
                            qty = :qty WHERE id=$id";

        $stmt = $conn->prepare($query);

        $stmt->bindParam(':user_id', $user_id);
        $stmt->bindParam(':share_name', $share_name);
        $stmt->bindParam(':purchase_amount', $purchase_amount);
        $stmt->bindParam(':provider', $provider);
        $stmt->bindParam(':qty', $qty);

        if($stmt->execute()){

            http_response_code(200);
            echo json_encode(array("success"=>true, "message" => "Share Updated Successfully."));
        }
        else{
            http_response_code(400);

            echo json_encode(array("success"=>false, "message" => "Unable to update share."));
        }
        
    }
}
else
{
    http_response_code(401);
    echo json_encode(array("success"=>false, "message" => "Action missing"));
}

function checkAuth($authHeader,$secret_key)
{

        $arr = explode(" ", $authHeader);


        /*echo json_encode(array(
            "message" => "sd" .$arr[1]
        ));*/

        $jwt = $arr[1];

        if($jwt){

            try {

                $decoded = JWT::decode($jwt, $secret_key, array('HS256'));

                // Access is granted. Add code of the operation here 

                return json_encode(array(
                    "success"=>true,
                    "message" => "Access granted:",
                    "error" => "",
                    "decoded"=>$decoded
                ));

            }catch (Exception $e){

            http_response_code(401);

            return  json_encode(array(
                "success"=>false,
                "message" => "Access denied.",
                "error" => "hello"
            ));
        }

        }
}
?> 

REACT login.js

import React, { useState,useEffect } from 'react'
import { useNavigate  } from 'react-router-dom'

const Login = (props) => {
    const host = "http://localhost/share_market_apis/api/api.php"; //process.env.REACT_APP_HOST;
    const [credentials, setCredentials] = useState({ email: "", password: "" })
    let navigate = useNavigate();

    useEffect(() => {
        props.setProgress(100)
      }, []);

    const handleSubmit = async (e) => {
        e.preventDefault();
        
        const response = await fetch(host, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({
                "action": "login",
                "email": credentials.email,
                "password": credentials.password
            })
        });

        // console.log(response); 
        const jsonTemp = await response.json();
        const json = JSON.parse(jsonTemp);
        if(json.success)
        {
            console.log(json);
           
        }
        else
        {
            props.showAlert("Invalid Credentails!","danger");
        }
    }

    const onChange = (e)=>{
        setCredentials({...credentials, [e.target.name]: e.target.value})
    }
    return (
        <div className='container my-3'>

        <h3>Login to continue</h3>
        <form onSubmit={handleSubmit}>
            <div className="mb-3">
                <label htmlFor="email" className="form-label">Email</label>
                <input type="email" className="form-control" id="email" name='email' value={credentials.email} onChange={onChange} />
            </div>
            <div className="mb-3">
                <label htmlFor="password" className="form-label">Password</label>
                <input type="password" className="form-control" id="password" value={credentials.password} name='password' onChange={onChange} />
            </div>

            <button type="submit" className="btn btn-primary">Login</button>
        </form>
       
    </div>
    )
}

export default Login
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • Did it help...? – nice_dev Jan 16 '22 at 05:12
  • Does this answer your question? [Cross-Origin Request Headers(CORS) with PHP headers](https://stackoverflow.com/questions/8719276/cross-origin-request-headerscors-with-php-headers) – Cilan Jan 19 '22 at 03:14

1 Answers1

-1

You seem to be missing to send a valid response for OPTIONS request. You need to return a valid response with valid headers for the OPTIONS preflight request like below:

<?php

include_once './config/database.php';
require "./vendor/autoload.php";
use \Firebase\JWT\JWT;

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Max-Age: 360000");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
header("content-type: application/json");

if(strtoupper($_SERVER["REQUEST_METHOD"]) == "OPTIONS"){
    echo json_encode([]);
    exit;
}
nice_dev
  • 17,053
  • 2
  • 21
  • 35