下面thinkphp框架教程欄目將給大家介紹thinkphp6如何通過全局中間件解決跨域問題,希望對(duì)需要的朋友有所幫助!
tp6 通過全局中間件 解決跨域問題
tp6官網(wǎng)有提供跨域決絕方法,當(dāng)我直接使用無法用。(可能我用的姿勢不對(duì))。
前端在Hbuildert中發(fā)送ajax請求,發(fā)生跨域。
get請求:可以通過后臺(tái)設(shè)置解決。
'Access-Control-Allow-Origin: *'。
post請求:會(huì)發(fā)生OPTIONS請求。在ajax請求中添加一個(gè)header頭信息。
header:{ 'Content-Type':'application/x-www-form-urlencoded' }
定義中間件
<?php declare (strict_types = 1); namespace appmiddleware; use thinkResponse; /** * 全局跨域請求處理 * Class CrossDomain * @package appmiddleware */ class CrossDomain { public function handle($request, Closure $next) { header('Access-Control-Allow-Origin: *'); header('Access-Control-Max-Age: 1800'); 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-CSRF-TOKEN, X-Requested-With, Token'); if (strtoupper($request->method()) == "OPTIONS") { return Response::create()->send(); } return $next($request); } }
在middleware.php中加入我們定義的中間件
然后跨域就好使了!