简体   繁体   中英

PHP - setcookie() is not working when called per axios request

I am currently developing a web application using PHP as my backend (with mySQL) and React in the frontend. To handle user authorization and authentication, I use JWT. To relogin the user automatically, if he still has a valid token, I want to store the JWT in a Cookie. However, the cookie is not set, when I call it per axios from my React app.

My (demo) code (PHP) ( http://localhost/rest/userService.php ):

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
include('./config/config.php');

if (isset($_GET['login'])) {
  setcookie('jwt', 'test', time() + 1800, '/');
  include('./config/jwt.php');
  echo login($con, json_decode(file_get_contents('php://input'), true));
}

?>

Everything is working fine, I get a valid token back. However, when I look in the Cookies in my F12 tools, no Cookie was set. If I call the function directly in the browser per

http://localhost/rest/userService.php?login

The cookie gets set and I also see it in my Cookies tab in the F12 tools.

Any suggestions why it does not work with axios?

Was able to resolve it myself. I added the following header to my .php file:

header('Access-Control-Allow-Credentials: true');

and added the following to my axios config:

withCredentials: true

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM