• 跨域配置-Access-Control-Allow-Origin


    //指定允许其他域名访问
    Access-Control-Allow-Origin:http://172.20.0.206
    //一般用法(*,指定域,动态设置)
    //是否允许后续请求携带认证信息(cookies),该值只能是true,否则不返回 Access-Control-Allow-Credentials:true

    //预检结果缓存时间 Access-Control-Max-Age: 1800

    //允许的请求类型 Access-Control-Allow-Methods:GET,POST,PUT,POST
    //允许的请求头字段 Access-Control-Allow-Headers:x-requested-with,content-type

    配置动态跨域

    Nginx

    #PHP-INFO-START
    if ($http_origin ~* "^(.*?).domain.com$") {
      set $cors_origin $http_origin; }
    if ($request_method = 'OPTIONS') {
      add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
      add_header Access-Control-Allow-Origin $cors_origin;
      add_header Access-Control-Allow-Credentials true;
      add_header Access-Control-Allow-Headers 'Content-Type,X-Requested-With';
      return 204;
    }
    #PHP-INFO-END

    PHP

    if (!empty($_SERVER["HTTP_ORIGIN"]) && strpos($_SERVER["HTTP_ORIGIN"], '.domain.com')) {
        header('Access-Control-Allow-Origin:' . $_SERVER["HTTP_ORIGIN"]);
        header('Access-Control-Allow-Credentials:true');
    }
    header('Access-Control-Allow-Methods:GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers:Content-Type,Origin,X-Requested-With');

    Axios

    Access-Control-Allow-Origin为 * 时不允许携带 Cookie
    (可通过动态设置域名配置允许跨域的域名)
    
    axios.defaults.withCredentials = true
    //需后台配置Access-Control-Allow-Credentials:true
    //若允许跨域的域名设置为 * 则不允许携带cookie此处须设置为 false

    ThinkPHP6中间件模式(多应用)

    <?php
    
    namespace appapimiddleware;
    
    use Closure;
    use thinkConfig;
    use thinkResponse;
    
    class AllowOriginMiddleware
    {
        protected $header = [
            //同源安全策略
            'Access-Control-Allow-Origin'   => 'test.domain.com',
            //预检结果缓存
            'Access-Control-Max-Age'        => 86400,
            //允许请求类型
            'Access-Control-Allow-Methods'  => 'GET,POST,OPTIONS',
            //允许请求头字段
            'Access-Control-Allow-Headers'  => 'Authorization, Content-Type, Origin',//允许携带Cookie
            //'Access-Control-Allow-Credentials'=>true
        ];
    
        public function handle($request, Closure $next, ?array $header = [])
        {
            $header = !empty($header) ? array_merge($this->header, $header) : $this->header;
    
            $origin = $request->header('origin');
            if ($origin) {
                $header['Access-Control-Allow-Origin'] = $origin;
            }
            else {
                $header['Access-Control-Allow-Origin'] = '*';
            }
    
            return $next($request)->header($header);
        }
    }

     在对应应用  middleware 中引用中间件

    return [
        appapimiddlewareAllowOriginMiddleware::class
    ];
  • 相关阅读:
    java-oop集合map
    IDEA启动Tomcat报错
    1.IDEM的快捷键
    1.idea快捷键
    14.
    13.级联一对多
    12.动态SQL
    11.动态参数
    10.主键回填
    9.参数的传递
  • 原文地址:https://www.cnblogs.com/xuanjiange/p/14736258.html
Copyright © 2020-2023  润新知