options 请求跨域问题处理

前后分离经常会出现跨域的问题,下面是工作中处理相关问题,总结的两种处理方法

一,中间件方式处理

针对laravel框架来说

    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $IlluminateResponse = 'Illuminate\Http\Response';
        $SymfonyResopnse = 'Symfony\Component\HttpFoundation\Response';
        $headers = [
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, PATCH, DELETE',
            'Access-Control-Allow-Headers' => 'token, X-Requested-With, Access-Control-Request-Method, Access-Control-Request-Headers, X-Token, Access-Token, Authorization, Origin, Content-Type, Cookie, Accept',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Expose-Headers', 'X-My-Custom-Header, X-Another-Custom-Header, Authorization, authenticated',
        ];

        // $response是`Illuminate\Http\Response`类的一个实例,
        // 而Passport实际上使用的是`Symfony\Component\HttpFoundation\Response`类响应消息
        if ($response instanceof $IlluminateResponse) {
            foreach ($headers as $key => $value) {
                $response->header($key, $value);
            }
            return $response;
        }

        if ($response instanceof $SymfonyResopnse) {
            foreach ($headers as $key => $value) {
                $response->headers->set($key, $value);
            }
            return $response;
        }
        return $response;
    }

当然,你可以进行更加细节的处理,就是哪些域名能够进行跨域$request对象可以获取地址

二,nginx服务器处理

添加header请求头信息,放到location外面

add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods POST, GET, OPTIONS, PUT, PATCH, DELETE;
add_header Access-Control-Allow-Headers X-Requested-With, Access-Control-Request-Method, Access-Control-Request-Headers, X-Token, Access-Token, Authorization, Origin, Content-Type, Cookie, Accept;
add_header Access-Control-Expose-Headers X-My-Custom-Header, X-Another-Custom-Header, Authorization, authenticated;

options 请求跨域问题处理


记录日常,分享,交流。

本作品采用《CC 协议》,转载必须注明作者和本文链接
希望你是真正的喜欢code
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 1
  • OPTIONS 请求应该处理完响应头就返回
  • 响应 OPTIONS 请求时应携带 Access-Control-Max-Age

www.ruanyifeng.com/blog/2016/04/co... 建议看看这篇文章

3年前 评论

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