亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Laravel 5.1 API啟用Cors

Laravel 5.1 API啟用Cors

嗶嗶one 2019-11-30 14:55:30
我一直在尋找一些方法來專門在laravel 5.1上啟用cors,我發現了一些庫,例如:https://github.com/neomerx/cors-illuminatehttps://github.com/barryvdh/laravel-cors但是他們都沒有專門針對Laravel 5.1的實現教程,我嘗試進行配置,但沒有用。如果有人已經在laravel 5.1上實現了CORS,我將非常感謝您的幫助...
查看完整描述

3 回答

?
慕森王

TA貢獻1777條經驗 獲得超3個贊

這是我的CORS中間件:


<?php namespace App\Http\Middleware;


use Closure;


class CORS {


    /**

     * Handle an incoming request.

     *

     * @param  \Illuminate\Http\Request  $request

     * @param  \Closure  $next

     * @return mixed

     */

    public function handle($request, Closure $next)

    {


        header("Access-Control-Allow-Origin: *");


        // ALLOW OPTIONS METHOD

        $headers = [

            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',

            'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'

        ];

        if($request->getMethod() == "OPTIONS") {

            // The client-side application can set only headers allowed in Access-Control-Allow-Headers

            return Response::make('OK', 200, $headers);

        }


        $response = $next($request);

        foreach($headers as $key => $value)

            $response->header($key, $value);

        return $response;

    }


}

要使用CORS中間件,您必須先在app \ Http \ Kernel.php文件中注冊它,如下所示:


protected $routeMiddleware = [

        //other middlewares

        'cors' => 'App\Http\Middleware\CORS',

    ];

然后您可以在路線中使用它


Route::get('example', array('middleware' => 'cors', 'uses' => 'ExampleController@dummy'));


查看完整回答
反對 回復 2019-11-30
?
Smart貓小萌

TA貢獻1911條經驗 獲得超7個贊

我總是使用一種簡單的方法。只需將以下行添加到\public\index.php文件即可。我認為您不必使用中間件。


header('Access-Control-Allow-Origin: *');  

header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');


查看完整回答
反對 回復 2019-11-30
?
繁花不似錦

TA貢獻1851條經驗 獲得超4個贊

我使用的是Laravel 5.4,不幸的是,盡管接受的答案似乎很好,但對于預檢請求(如PUT和DELETE),該OPTIONS請求將在請求之前,在$routeMiddleware數組中指定中間件(并在路由定義文件中使用),除非您也定義一個路由處理程序OPTIONS。這是因為如果沒有OPTIONS路由,Laravel將在內部響應該方法而沒有CORS標頭。


簡而言之,要么在$middleware數組中定義針對所有請求全局運行的中間件,要么在其中進行操作,$middlewareGroups或者$routeMiddleware為定義路由處理程序OPTIONS??梢赃@樣完成:


Route::match(['options', 'put'], '/route', function () {

    // This will work with the middleware shown in the accepted answer

})->middleware('cors');

我還出于相同的目的編寫了一個中間件,該中間件看起來很相似,但是由于試圖更好地配置和處理一系列條件,因此其尺寸更大:


<?php


namespace App\Http\Middleware;


use Closure;


class Cors

{

    private static $allowedOriginsWhitelist = [

      'http://localhost:8000'

    ];


    // All the headers must be a string


    private static $allowedOrigin = '*';


    private static $allowedMethods = 'OPTIONS, GET, POST, PUT, PATCH, DELETE';


    private static $allowCredentials = 'true';


    private static $allowedHeaders = '';


    /**

     * Handle an incoming request.

     *

     * @param  \Illuminate\Http\Request  $request

     * @param  \Closure  $next

     * @return mixed

     */

    public function handle($request, Closure $next)

    {

      if (! $this->isCorsRequest($request))

      {

        return $next($request);

      }


      static::$allowedOrigin = $this->resolveAllowedOrigin($request);


      static::$allowedHeaders = $this->resolveAllowedHeaders($request);


      $headers = [

        'Access-Control-Allow-Origin'       => static::$allowedOrigin,

        'Access-Control-Allow-Methods'      => static::$allowedMethods,

        'Access-Control-Allow-Headers'      => static::$allowedHeaders,

        'Access-Control-Allow-Credentials'  => static::$allowCredentials,

      ];


      // For preflighted requests

      if ($request->getMethod() === 'OPTIONS')

      {

        return response('', 200)->withHeaders($headers);

      }


      $response = $next($request)->withHeaders($headers);


      return $response;

    }


    /**

     * Incoming request is a CORS request if the Origin

     * header is set and Origin !== Host

     *

     * @param  \Illuminate\Http\Request  $request

     */

    private function isCorsRequest($request)

    {

      $requestHasOrigin = $request->headers->has('Origin');


      if ($requestHasOrigin)

      {

        $origin = $request->headers->get('Origin');


        $host = $request->getSchemeAndHttpHost();


        if ($origin !== $host)

        {

          return true;

        }

      }


      return false;

    }


    /**

     * Dynamic resolution of allowed origin since we can't

     * pass multiple domains to the header. The appropriate

     * domain is set in the Access-Control-Allow-Origin header

     * only if it is present in the whitelist.

     *

     * @param  \Illuminate\Http\Request  $request

     */

    private function resolveAllowedOrigin($request)

    {

      $allowedOrigin = static::$allowedOrigin;


      // If origin is in our $allowedOriginsWhitelist

      // then we send that in Access-Control-Allow-Origin


      $origin = $request->headers->get('Origin');


      if (in_array($origin, static::$allowedOriginsWhitelist))

      {

        $allowedOrigin = $origin;

      }


      return $allowedOrigin;

    }


    /**

     * Take the incoming client request headers

     * and return. Will be used to pass in Access-Control-Allow-Headers

     *

     * @param  \Illuminate\Http\Request  $request

     */

    private function resolveAllowedHeaders($request)

    {

      $allowedHeaders = $request->headers->get('Access-Control-Request-Headers');


      return $allowedHeaders;

    }

}


查看完整回答
反對 回復 2019-11-30
  • 3 回答
  • 0 關注
  • 855 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號