Laravel 5.2 CORS,GET不适用于预检OPTIONS

sun*_*kid 23 php cors laravel vue.js laravel-5.2

可怕的CORS错误:

跨源请求已阻止:同源策略禁止在http:// localhost/mysite/api/test中读取远程资源.(原因:缺少CORS标题'Access-Control-Allow-Origin').

Laravel路线:

$router->group(['prefix' => 'api', 'middleware' => 'cors'], function ($router) {
    $router->get('/test', 'MyController@myMethod');
});
Run Code Online (Sandbox Code Playgroud)

Laravel Cors Middlware:

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, Authorization'
        ];
        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;
    }
Run Code Online (Sandbox Code Playgroud)

Laravel内核:

 protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'cors' => \App\Http\Middleware\CORS::class
    ];
Run Code Online (Sandbox Code Playgroud)

相关.htaccess:

RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
Run Code Online (Sandbox Code Playgroud)

相关的Vue.js:

 new Vue({
        el: '#app',
        data: {
           //data here
        },
        http: {
            headers: {
                "Authorization": "Basic " + "apiKeyHere"
            }
        },
        methods: {
            mymethod: function (e)
            {
                e.preventDefault();
                this.$http.get('http://localhost/mysite/api/test').then(
                        function (response)
                        {
                          //do something
                        }
                )
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

如果我取出Authorization标头选项,则请求有效.

我也试过https://github.com/barryvdh/laravel-cors但仍然没有喜悦.任何帮助赞赏!

sun*_*kid 25

显然不是理想的解决方案,但它的工作原理.我已经将它添加到我的routes.php文件的顶部:

header('Access-Control-Allow-Origin: *');
header( 'Access-Control-Allow-Headers: Authorization, Content-Type' );
Run Code Online (Sandbox Code Playgroud)

如果没有黑客攻击,这将是很好的...唉.

更新:原来是IIS相关.我最终在web.config文件中设置了标题,现在CORS可以在不破坏routes.php文件的情况下工作.

<httpProtocol>
    <customHeaders>
       <add name="Access-Control-Allow-Headers" value="Origin, Authorization, X-Requested-With, Content-Type, Accept" />
       <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS,PUT,DELETE" />
    </customHeaders>
</httpProtocol>
Run Code Online (Sandbox Code Playgroud)

如果要限制访问,可以添加出站规则:

      <outboundRules>
          <clear />
                <rule name="AddCrossDomainHeader">
                    <match serverVariable="RESPONSE_Access_Control_Allow_Origin" pattern=".*" />
                    <conditions logicalGrouping="MatchAll" trackAllCaptures="true">
                        <add input="{HTTP_ORIGIN}" pattern="(http(s)?://((.+\.)?somesite\.com|(.+\.)?anothersite\.org))" />
                    </conditions>
                    <action type="Rewrite" value="{C:0}" />
                </rule>
      </outboundRules>
Run Code Online (Sandbox Code Playgroud)

  • 您究竟将它们放在web.config中的什么位置?我把它们放在&lt;system.webServer&gt;之后,但是不起作用。另外我不使用IIS,我正在使用docker / nginx,我仍然必须这样做吗? (2认同)

M A*_*fan 15

我解决了我的问题,只需在我的routes.php上添加这些行.Laravel 5.2在routes/web.php中大于5.2

header('Access-Control-Allow-Origin:  *');
header('Access-Control-Allow-Methods:  POST, GET, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers:  Content-Type, X-Auth-Token, Origin, Authorization');
Run Code Online (Sandbox Code Playgroud)

或者在全局HTTP中间件堆栈中注册Cors中间件

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\CorsMiddleware::class
];
Run Code Online (Sandbox Code Playgroud)


Utw*_*two 8

您的中间件还可以,但您需要在全局HTTP中间件堆栈中注册Cors中间件.

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\CorsMiddleware::class
];
Run Code Online (Sandbox Code Playgroud)


eit*_*hed 5

问题实际上是由预检请求引起的,但是当我们谈论Laravel时,处理方式需要一些额外的解释-主要是OPTIONS请求被路由(其他答案更像是PHP方式,而不是Laravel方式),所以,您必须将其添加到您的路线中才能成功:

Route::options('/{any}', function(){ return ''; })->where('any', '.*');

现在,让我们迎合所有其他方法-创建CORS中间件:

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)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE');
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,对于给定的路由,使用该中间件:

Route::put('/test', function(){ echo('test'); })->with('cors');