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

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.
305 2 2
2个回答

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转发,亲测可用。

  • wangsky522 7天前

    本地也是这样 在同一个局域网 前端好像需要的配置代理,但是用fastadmin就不会碰到这种问题

TM

如果使用了路由也需要在路由里面配置的Route::fallback(function(Request $request){
$response = strtoupper($request->method()) === 'OPTIONS' ?
response('', 204) : response(json(['code' => 404, 'message' => '没有你想要的数据,请检查是否访问正确!']), 404);
$response->withHeaders([
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Allow-Origin' => "",
'Access-Control-Allow-Methods' => '
',
'Access-Control-Allow-Headers' => '*',
]);
return $response;
// return json(['code' => 404, 'message' => '没有你想要的数据,请检查是否访问正确!']);
});
好像是没走到中间件的问题

  • 暂无评论
×
🔝