Laravel 自定义中间件解决跨域问题 header 头不生效,有人解决过此类问题吗?

中间件核心代码如下:

public function handle($request, Closure $next)
    {
        $response = $next($request);
        //允许请求来自哪些域名
        $response->header('Access-Control-Allow-Origin', '*');
        //允许请求中包含哪些header
        $response->header('Access-Control-Allow-Headers', 'token,Origin, X-Requested-With, Content-Type, Accept');
        //允许请求采用哪些请求方式
        $response->header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
        //允许请求中携带cookie
        $response->header('Access-Control-Allow-Credentials', 'true');
        //自定义的请求头token
        $response->header('Access-Control-Expose-Headers', 'token');
        return $response;
    }

问题描述:
添加了header头 token时 报不允许Origin
不添加header头 token时 不同域名之间接口可以正常请求

《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 5

要不试试我的?

$headers = [
        'Access-Control-Allow-Origin'      => '*',
        'Access-Control-Allow-Methods'     => 'POST, GET, OPTIONS',
        'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Max-Age'           => '86400',
        'Access-Control-Allow-Headers'     => 'Content-Type, Authorization, X-Requested-With'
    ];

    if ($request->isMethod('OPTIONS'))
    {
        return response()->json('{"method":"OPTIONS"}', 200, $headers);
    }

    $response = $next($request);

    foreach($headers as $key => $value)
    {
        $response->header($key, $value);
    }

    return $response;
5年前 评论

@BANice 我的是自定义了一个header头 token不行 不自定义header头没问题

5年前 评论
ThinkQ

可以

5年前 评论

碰到了同样的问题,只要是header里添加的自定义的内容就会跨域失败 楼主问题怎么解决的

4年前 评论

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