后端配置了跨域请求但是前端一直跨域

wangsky522

问题描述

这里详细描述问题
后端配置了跨域请求但是前端一直跨域

程序代码

 public function process(Request|\Webman\Http\Request $request, callable $handler): Response
    {
        // 设置 CORS 相关头部
        $response = $handler($request);

        // 设置允许跨域的域名,* 表示允许所有域
        $response->withHeaders([
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
            'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Accept, Authorization',
            'Access-Control-Allow-Credentials' => 'true',
        ]);

        // 处理预检请求(OPTIONS)
        if ($request->method() == 'OPTIONS') {
            return $response->withHeaders([
                'Access-Control-Allow-Origin' => '*',
                'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
                'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Accept, Authorization',
                'Access-Control-Max-Age' => '86400', // 预检缓存时间,单位秒
            ]);
        }

        return $response;
    }

报错信息

 Access to XlLHttpReguest at 'http://app.xianggangkdhub. xyz/api/login’from origin
http://localhost:8080’ has been blocked by CokS policy: Response to preflight request doesn't pass access
control check: No ’Access-Control-Allow-0rigin’header is present on the requested resource.
106 1 0
1个回答

jack10082009

看一下有没有使用Nginx转发https到http,如果是的话可以配置Nginx实现预检返回允许。

add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Credentials   'true';
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'x-csrf-token,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {return 200;}

我用的Nginx转发,亲测可用。

  • 暂无评论
×
🔝