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时 不同域名之间接口可以正常请求

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 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年前 评论

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