[记录] 简单的跨域中间件

后置中间件 application/http/middleware/CORS.php

<?php

namespace app\http\middleware;

class CORS
{
    public function handle($request, \Closure $next)
    {
        $response = $next($request);
        $origin = $request->server('HTTP_ORIGIN') ?: '';
        $allow_origin = [
            'https://gleehub.com',
        ];
        if (in_array($origin, $allow_origin)) {
            $response->header('Access-Control-Allow-Origin', $origin);
            $response->header('Access-Control-Allow-Headers', 'Authorization, Content-Type, Accept, Origin, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With');
            $response->header('Access-Control-Expose-Headers', 'Authorization, authenticated');
            $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
            $response->header('Access-Control-Allow-Credentials', 'true');
        }
        return $response;
    }
}

ThinkPHP >= 5.1

HTTP 参考文档

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 9

tp5.1不是自带了cors吗,在路由里面使用

4年前 评论
cnguu (楼主) 4年前
lmaster

赞。

4年前 评论

好像咋没有这个 HTTP_ORIGIN

4年前 评论
cnguu

@Morrow

第十行代码

$origin = $request->server('HTTP_ORIGIN') ?: '';
4年前 评论

@cnguu 好像$request->server里没有 HTTP_ORIGIN 这个吧,环境不同么

4年前 评论
cnguu

@Morrow

跨域请求才会存在 HTTP_ORIGIN

4年前 评论
VeryCool

:blush: :blush: 一直在用5.0 5.1有点过度 毕竟下一版本直接6.0了

4年前 评论
cnguu

@VeryCool 都行,中间件通用

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!