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
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。