javascript - 设置 cookie 不出现在 Axios 和 Fetch 中

标签 javascript reactjs symfony

我使用我的 API 端点进行身份验证,并在使用 postman 测试时在响应中使用 Lexik JWT token 设置仅 http 的 cookie,一切正常,cookie 设置正确,需要注意的是 CORS 是通过 Nelmio Cors Bundle 启用的。

nelmio_cors:
    defaults:
        allow_credentials: true
        origin_regex: true
        allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
        allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
        allow_headers: ['Access-Control-Allow-Origin', 'X-Requested-With', 'X-HTTP-Method-Override', 'Content-Type', 'Accept']
        expose_headers: ['Link']
        max_age: 3600

这是LexikEvents::AUTHENTICATION_SUCCESS

<?php

namespace App\EventSubscriber;

use Symfony\Component\HttpFoundation\Response;
use Lexik\Bundle\JWTAuthenticationBundle\Events as LexikEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
use Symfony\Component\HttpFoundation\Cookie;

class LexikLoginSuccessSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            LexikEvents::AUTHENTICATION_SUCCESS => ['onAuthenticationSuccess']
        ];
    }

    public function onAuthenticationSuccess(AuthenticationSuccessEvent $event)
    {
        /** @var Response $response */
        $response = $event->getResponse();

        $hourLater = (new \DateTime())->modify('+1hours');
        $cookie = new Cookie('jwt_token', $event->getData()['token'], $hourLater);
        $response->headers->setCookie($cookie);
    }
}

最后是 fetch 和 axios 配置

const onSubmit = e => {
    e.preventDefault();

    fetch('http://127.0.0.1:8000/api/get-cookies', {
      method: 'POST',
      credentials: 'include',
      body: JSON.stringify({
        username: form.username,
        password: form.password,
      }),
      headers: {
        "Content-Type": "application/json",
      }
    })
    .then( response => response.json()).then( json => console.log(json)).catch( error => console.log(error));

    Axios.post('http://127.0.0.1:8000/api/get-cookies', {
      username: form.username,
      password: form.password,
    }, {
      withCredentials: true,
      maxRedirects: 0,
      headers: {
        "Content-Type": "application/json",
      }
    }).then(response => console.log(response)).catch( error => console.log(error));
  }

触发 onSubmit 函数后,响应确实是 JWT token ,但 SET COOKIE header 不存在,并且未设置 cookie。

最佳答案

经过 3 个小时的 axios 文档研究,阅读了大量建议不同修复和测试的类似问题,我终于得出以下结论:

第1步:
对于 AXIOS 确保将配置中的 withCredentials 设置为 true(如果没有,您可能会丢失它,您只需转到下一步即可)

config = { ...yourConfig, withCredentials: true }
Axios.post(url, data, config).then.....

请注意,maxRedirects 不是必需的(有问题的代码)
对于 FETCH,请确保将配置中的凭据设置为“包含”(如果没有,您可能会丢失它,那么您只需转到下一步即可)

config = { ...yourConfig, credentials: "include"
fetch(url, config).then....


第 2 步:
这是有趣的部分,您的服务器是否运行在 localhost 域之外的其他域(例如 127.0.0.1:8000 url)上?这是谷歌浏览器和基于 Chrome 引擎的浏览器将阻止来自任何端口后缀 URL 的 Cookie(我不确定其他浏览器,但以防万一在 http://localhost - 127.0.0.1:80 上为您的后端提供服务,请使用主机文件要将您的网址映射到域,请使用 localtunnel/ngrok 以防万一您的浏览器决定提示您的后端网址)

现在,您应该已准备好存储来自响应的跨源 http only cookie,无论后端语言如何,在启用 CORS 后,它应该几乎相同。

关于javascript - 设置 cookie 不出现在 Axios 和 Fetch 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60384406/

相关文章:

javascript - 获取通过其链接连接的所有节点

javascript - 如何在react中删除数组中的元素?

使用 Vuejs+Webpack 时的 Symfony 3 项目结构

php - 交响乐 2 : route defined in annotation not visible from by Twig's path()

php - 如何使用 Join 和 where 子句从多个表中获取数据

javascript - Nativescript-Vue MobileApp : Axios return status:null and data :""

javascript - 将 Chartjs 与 reactjs 结合使用

javascript - 这个带有可变引用参数的 JavaScript 函数是纯函数吗?

javascript - React-admin 在共享相同资源的两个列表上分隔过滤器

javascript - React Router 中页面更改时更新状态