在前后端分離項目中,如通過thinkphp6開發api,涉及前端調用跨域問題,可通過自帶的跨域中間件解決。
在middleware.php
中,設置
<?php
// 全局中間件定義文件
return [
\think\middleware\AllowCrossDomain::class
];
等同於原生PHP中下面幾行代碼的效果。
<?php
header('Content-Type: text/html;charset=utf-8');
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin');