一文詳解thinkphp6如何通過(guò)全局中間件解決跨域問(wèn)題

下面thinkphp框架教程欄目將給大家介紹thinkphp6如何通過(guò)全局中間件解決跨域問(wèn)題,希望對(duì)需要的朋友有所幫助!

tp6 通過(guò)全局中間件 解決跨域問(wèn)題

tp6官網(wǎng)有提供跨域決絕方法,當(dāng)我直接使用無(wú)法用。(可能我用的姿勢(shì)不對(duì))。

前端在Hbuildert中發(fā)送ajax請(qǐng)求,發(fā)生跨域。

get請(qǐng)求:可以通過(guò)后臺(tái)設(shè)置解決。

'Access-Control-Allow-Origin: *'。

post請(qǐng)求:會(huì)發(fā)生OPTIONS請(qǐng)求。在ajax請(qǐng)求中添加一個(gè)header頭信息。

header:{     'Content-Type':'application/x-www-form-urlencoded' }

定義中間件

<?php declare (strict_types = 1);  namespace appmiddleware; use thinkResponse;  /**  * 全局跨域請(qǐng)求處理  * 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中加入我們定義的中間件

一文詳解thinkphp6如何通過(guò)全局中間件解決跨域問(wèn)題

然后跨域就好使了!

立即學(xué)習(xí)PHP免費(fèi)學(xué)習(xí)筆記(深入)”;

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點(diǎn)贊11 分享