跨域配置-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 app\api\middleware;

use Closure;
use think\Config;
use think\Response;

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 [
    app\api\middleware\AllowOriginMiddleware::class
];

 

posted @ 2021-05-06 17:58  悬剑丶  阅读(7314)  评论(0编辑  收藏  举报