I am running a react app on localhost:3000. I made an axios request to my backend on the default XAMPP localhost to setcookie. In previous attempts, I am able to setcookie if my frontend is in the default XAMPP localhost. But since switching to the react dev server, localhost:3000. I am unable to set cookie.
Here is my php file:
header("Access-Control-Allow-Origin: *");
require __DIR__ . './vendor/autoload.php';
use \Firebase\JWT\JWT;
if(isset($_POST)){
//grab secret key from .env file, remember to exclude from gitignore.
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
$key = $_ENV['SECRET_KEY'];
//access post data to for jwt creation
$data = json_decode(file_get_contents("php://input"), true);
$timezone = new DateTimeZone('Asia/Kuching');
$expiry = new DateTime();
$expiry->setTimezone($timezone);
$expiry->modify("+2 days");
$date = $expiry->format("Y-m-d H:i:s.v");
$payload = array(
"ttl"=>$date,
"data"=>$data['tokenValue']
);
$jwt = JWT::encode($payload,$key);
setcookie("accessToken",$jwt,[
'expires'=>$date,
'path'=>'/',
'domain'=>'localhost',
'secure'=>false,
'httponly'=>true,
'samesite'=>'None'
]);
}
What could be wrong? I did change the domain from 'localhost' to 'localhost:3000' but it still does not work.
Found a solution based on this question .
First on the react app, in the axios method, do this:
axios
.post(url, JSON.stringify(payload), {
withCredentials: true,
}).then(....)
You need to add credentials true header in the request header. Do the same in the php file.
At the beginning of the file do this,
header("Access-Control-Allow-Origin: http://localhost:3000");
header("Access-Control-Allow-Credentials: true");
Before, access-control-allow-origin is set to *. But for the sake of setting a cookie for localhost:3000, we do so. Also include the allow-credentials, because we send the axios request withCredentials true.
It should work now.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.