這里詳細(xì)描述問題
后端配置了跨域請求但是前端一直跨域
public function process(Request|\Webman\Http\Request $request, callable $handler): Response
{
// 設(shè)置 CORS 相關(guān)頭部
$response = $handler($request);
// 設(shè)置允許跨域的域名,* 表示允許所有域
$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',
]);
// 處理預(yù)檢請求(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', // 預(yù)檢緩存時間,單位秒
]);
}
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.
看一下有沒有使用Nginx轉(zhuǎn)發(fā)https到http,如果是的話可以配置Nginx實(shí)現(xiàn)預(yù)檢返回允許。
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轉(zhuǎn)發(fā),親測可用。
這個跟在不在同一個局域網(wǎng)是沒有關(guān)系的,你說fastadmin沒有這個問題,說明它在返回的response中添加了相關(guān)的cors頭。這個你可以查一下cors相關(guān)的東西。只有域名一樣端口一樣,才被認(rèn)定為同域。不同域的話,瀏覽器會先進(jìn)行option請求(預(yù)檢),只有預(yù)檢返回的header中含有我剛剛貼上來的代碼這些header,才會發(fā)起正式請求。
如果使用了路由也需要在路由里面配置的Route::fallback(function(Request $request){
$response = strtoupper($request->method()) === 'OPTIONS' ?
response('', 204) : response(json(['code' => 404, 'message' => '沒有你想要的數(shù)據(jù),請檢查是否訪問正確!']), 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' => '沒有你想要的數(shù)據(jù),請檢查是否訪問正確!']);
});
好像是沒走到中間件的問題