搜尋
首頁php框架Laravellaravel 跨域解決方案

laravel 跨域解決方案

Oct 22, 2019 pm 01:26 PM
laravel

我們在用laravel 進行開發的時候,特別是前後端完全分離的時候,由於前端項目運行在自己機器的指定端口(也可能是其他人的機器) , 例如localhost:8000 , 而laravel 程序又運行在另一個端口,這樣就跨域了,而由於瀏覽器的同源策略,跨域請求是非法的。其實這個問題很好解決,只要增加一個中間件就可以了。

1.新建一個中間件

php artisan make:middleware EnableCrossRequestMiddleware

2.書寫中間件內容

<?php
namespace App\Http\Middleware;
use Closure;
class EnableCrossRequestMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $origin = $request->server(&#39;HTTP_ORIGIN&#39;) ? $request->server(&#39;HTTP_ORIGIN&#39;) : &#39;&#39;;
        $allow_origin = [
            &#39;http://localhost:8000&#39;,
        ];
        if (in_array($origin, $allow_origin)) {
            $response->header(&#39;Access-Control-Allow-Origin&#39;, $origin);
            $response->header(&#39;Access-Control-Allow-Headers&#39;, &#39;Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN&#39;);
            $response->header(&#39;Access-Control-Expose-Headers&#39;, &#39;Authorization, authenticated&#39;);
            $response->header(&#39;Access-Control-Allow-Methods&#39;, &#39;GET, POST, PATCH, PUT, OPTIONS&#39;);
            $response->header(&#39;Access-Control-Allow-Credentials&#39;, &#39;true&#39;);
        }
        return $response;
    }
}

$allow_origin 陣列變數就是你允許跨域的列表了,可自行修改。

3.然後在核心檔案註冊該中間件

    protected $middleware = [
        // more
        App\Http\Middleware\EnableCrossRequestMiddleware::class,
    ];

在App\Http\Kernel 類別的$middleware 屬性添加,這裡註冊的中間件屬於全域中間件。

然後你會發現前端頁面已經可以發送跨域請求了。

會多出一次 method 為 options 的請求是正常的,因為瀏覽器要先判斷該伺服器是否允許該跨網域請求。

更多Laravel相關技術文章,請造訪Laravel框架入門教學專欄進行學習!

以上是laravel 跨域解決方案的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:segmentfault。如有侵權,請聯絡admin@php.cn刪除
最新的Laravel版本:DIFES DISCON最新的Laravel版本:DIFES DISCONMay 12, 2025 am 12:15 AM

Laravel10IntroducessEveralKeyFeatUrestHatenHanceWebDevelopment.1)LazyCollectionsAllyCollefficeProcesingOflargeFlargedAtasetSwithSwithOutloadingAllRecordSintomeMemory.2)the Make:Model Model Moged-and-Mogration'ArtisanCommandSancancMommandSimplififieScreatingModeltigation.3)

Laravel遷移解釋了:創建,修改和管理您的數據庫Laravel遷移解釋了:創建,修改和管理您的數據庫May 12, 2025 am 12:11 AM

laravelmigrationssshouldbeusedbecausetheystreamlinedeplupment,nesurecresistencyAcrossenviments和simplifyCollaborationAndDeployment.1)shemallogragrammatonofdatabaseschemachanges,ReeducingErrors.2)MigrigationScanBeverCanbeverSionConconconconcontrollin.2)

Laravel遷移:值得使用嗎?Laravel遷移:值得使用嗎?May 12, 2025 am 12:10 AM

是的。

Laravel:軟刪除了性能問題Laravel:軟刪除了性能問題May 12, 2025 am 12:04 AM

SoftDeletesinLaravelimpactperformancebycomplicatingqueriesandincreasingstorageneeds.Tomitigatetheseissues:1)Indexthedeleted_atcolumntospeedupqueries,2)Useeagerloadingtoreducequerycount,and3)Regularlycleanupsoft-deletedrecordstomaintaindatabaseefficie

Laravel遷移對什麼有益?用例和福利Laravel遷移對什麼有益?用例和福利May 11, 2025 am 12:14 AM

Laravelmigrationsarebeneficialforversioncontrol,collaboration,andpromotinggooddevelopmentpractices.1)Theyallowtrackingandrollingbackdatabasechanges.2)Migrationsensureteammembers'schemasstaysynchronized.3)Theyencouragethoughtfuldatabasedesignandeasyre

如何在Laravel中使用軟刪除:保護您的數據如何在Laravel中使用軟刪除:保護您的數據May 11, 2025 am 12:14 AM

Laravel的軟刪除功能通過標記記錄而非實際刪除來保護數據。 1)在模型中添加SoftDeletestrait和deleted_at字段。 2)使用delete()方法標記刪除,使用restore()方法恢復。 3)查詢時使用withTrashed()或onlyTrashed()包含軟刪除記錄。 4)定期清理超過一定時間的軟刪除記錄以優化性能。

Laravel遷移是什麼,您如何使用它們?Laravel遷移是什麼,您如何使用它們?May 11, 2025 am 12:13 AM

laravelmigrationSareversionControlfordatabaseschemas,允許Roducibleandreversiblechanges.tousethem:1)creatighatsanmake:遷移',2)定義chemachangesinthe'up()

Laravel遷移:回滾行不通,發生了什麼事?Laravel遷移:回滾行不通,發生了什麼事?May 11, 2025 am 12:10 AM

Laravelmigrationsmayfailtorollbackduetodataintegrityissues,foreignkeyconstraints,orirreversibleactions.1)Dataintegrityissuescanoccurifamigrationaddsdatathatcan'tbeundone,likeacolumnwithadefaultvalue.2)Foreignkeyconstraintscanpreventrollbacksifrelatio

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具