美文网首页
Laravel 中遇到跨域请求的解决方法

Laravel 中遇到跨域请求的解决方法

作者: 晨曦入诗 | 来源:发表于2022-03-30 10:12 被阅读0次

使用 Sesssion-Cookie 验证机制遇到的跨域请求,无法获取到 Cookie 的问题?

  • 1、由于 HTTP 协议决定跨域无法传递 cookie ,所以发生跨域(前端所在的服务器域名)请求时浏览器是无法获取到 Cookie 的。
  • 解决方法:
    (1)修改 config/session.php 文件
<?
······
······
    /*
    |--------------------------------------------------------------------------
    | Same-Site Cookies
    |--------------------------------------------------------------------------
    |
    | This option determines how your cookies behave when cross-site requests
    | take place, and can be used to mitigate CSRF attacks. By default, we
    | will set this value to "lax" since this is a secure default value.
    |
    | Supported: "lax", "strict", "none", null
    |
    */

    // none is only for local test environment !!!
    'same_site' => 'none',

(2)修改 config/cors.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['api/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],

    'allowed_origins' => [
        'https://api.hvn-dev.waroku.com',
        'https://hvn-dev.waroku.com',
        'http://localhost:3000'    // is only for local testing
    ],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    // true : Cookies CORS ( only for local testing)
    'supports_credentials' => true,

];

相关文章

网友评论

      本文标题:Laravel 中遇到跨域请求的解决方法

      本文链接:https://www.haomeiwen.com/subject/muuijrtx.html