thinkphp 5 跨域問題解決

大尹發表於2024-03-14

版本:5.1.41 LTS

從網上搜到好多從/public/index.php 新增heade資訊,或者用中介軟體,或者新增behavior操作,可以做到解決跨域問題,但是親身試驗了都不行,今天剛找了一個,可以使用,放在這裡

header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With');
header('Access-Control-Allow-Origin: *');
// 支援事先使用靜態方法設定Request物件和Config物件
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
    //允許的源域名
    header("Access-Control-Allow-Origin: *");
    //允許的請求頭資訊
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization,token");
    //允許的請求型別
    header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
    exit;
}

相關文章