Laravel 5.1 API启用Cors

时间:2015-10-12 08:40:27

标签: php api laravel cors laravel-5.1

我已经找了一些方法来启用laravel 5.1上的cors,我发现了一些类似的库:

https://github.com/neomerx/cors-illuminate

https://github.com/barryvdh/laravel-cors

但是他们都没有专门针对Laravel 5.1的实现教程,我尝试配置但它不起作用。

如果有人已经在laravel 5.1上实施了CORS,我将非常感谢帮助...

8 个答案:

答案 0 :(得分:51)

这是我的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'));

答案 1 :(得分:24)

我总是使用简单的方法。只需将以下行添加到\public\index.php文件即可。你不必使用我认为的中间件。

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

答案 2 :(得分:5)

barryvdh/laravel-cors与Laravel 5.1完美配合,只有几个关键点启用它。

  1. 将其添加为作曲家依赖项后,请确保已发布CORS配置文件并根据需要调整CORS标头。以下是 app / config / cors.php

    中的内容
    <?php
    
    return [
    
        'supportsCredentials' => true,
        'allowedOrigins' => ['*'],
        'allowedHeaders' => ['*'],
        'allowedMethods' => ['GET', 'POST', 'PUT',  'DELETE'],
        'exposedHeaders' => ['DAV', 'content-length', 'Allow'],
        'maxAge' => 86400,
        'hosts' => [],
    ];
    
  2. 在此之后,还有一个步骤未在文档中提及,您必须在App内核中添加CORS处理程序'Barryvdh\Cors\HandleCors'。我更喜欢在全球中间件堆栈中使用它。喜欢这个

    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
        'Illuminate\Cookie\Middleware\EncryptCookies',
        'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
        'Illuminate\Session\Middleware\StartSession',
        'Illuminate\View\Middleware\ShareErrorsFromSession',
    
        'Barryvdh\Cors\HandleCors',
    
    ];
    

    但是由您决定将其用作路由中间件并放置在特定路由上。

  3. 这应该使包使用L5.1

答案 3 :(得分:5)

我正在使用Laravel 5.4,不幸的是,虽然接受的答案看起来很好,但对于预先发出的请求(例如PUTDELETE),前面会有一个OPTIONS请求,指定中间件除非您为$routeMiddleware定义路由处理程序,否则在OPTIONS数组中(并在路由定义文件中使用它)将不起作用。这是因为没有OPTIONS路由,Laravel将internally respond添加到没有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;
    }
}

此外还写了blog post

答案 4 :(得分:4)

对我来说,我将此代码放在public\index.php文件中。并且对所有CRUD操作都正常。

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS, post, get');
header("Access-Control-Max-Age", "3600");
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Access-Control-Allow-Credentials", "true");

答案 5 :(得分:0)

只需将其用作中间件

<?php

namespace App\Http\Middleware;

use Closure;

class CorsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $response->header('Access-Control-Allow-Origin', '*');
        $response->header('Access-Control-Allow-Methods', '*');

        return $response;
    }
}

并在此路径app/Http/Kernel.php上的中间文件中注册中间件到您喜欢的组中,一切正常

答案 6 :(得分:0)

在浪费了很多时间之后,我终于发现了这个愚蠢的错误,这可能也对您有帮助。

如果您无法通过函数关闭或控制器操作从路由返回响应,则它将无法正常工作。

示例:

关闭

Route::post('login', function () {
    return response()->json(['key' => 'value'], 200); //Make sure your response is there.
});

控制器操作

Route::post('login','AuthController@login');

class AuthController extends Controller {

     ...

     public function login() {
          return response()->json(['key' => 'value'], 200); //Make sure your response is there.
     }

     ...

}

测试CORS

Chrome->开发人员工具->网络标签

enter image description here

如果出现任何问题,那么您的响应头将不会在这里。

答案 7 :(得分:0)

https://github.com/fruitcake/laravel-cors

使用此库。请按照此仓库中的说明进行操作。

请记住不要在CORS URL中使用nullNullPointerException,因为此库无法使用。始终将return与CORS URL一起使用。

谢谢