Laravel 5.2 CORS,GET 不使用预检选项 [英] Laravel 5.2 CORS, GET not working with preflight OPTIONS

查看:33
本文介绍了Laravel 5.2 CORS,GET 不使用预检选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可怕的 CORS 错误:

The dreaded CORS Error:

跨域请求被阻止:同源策略不允许读取http://localhost/mysite/api/test 上的远程资源.(原因:CORS标题Access-Control-Allow-Origin"丢失).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/mysite/api/test. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

Laravel 路线:

Laravel route:

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

Laravel Cors 中间件:

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;
    }

Laravel 内核:

Laravel Kernel:

 protected $routeMiddleware = [
        'auth' => AppHttpMiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
        'cors' => AppHttpMiddlewareCORS::class
    ];

相关.htaccess:

Relevant .htaccess:

RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

相关的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
                        }
                )
            }
        }
    });

如果我去掉 Authorization 标头选项,则请求有效.

If I take out the Authorization header option the request works.

我也尝试过 https://github.com/barryvdh/laravel-cors,但仍然没有任何乐趣.任何帮助表示赞赏!

I've also tried https://github.com/barryvdh/laravel-cors but still no joy. Any help appreciated!

推荐答案

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

Clearly not the ideal solution but it WORKS. I've added this to the top of my routes.php file:

header('Access-Control-Allow-Origin: *');
header( 'Access-Control-Allow-Headers: Authorization, Content-Type' );

在没有黑客的情况下让它工作会很好......唉.

It would be nice to get this working without a hack... alas.

更新:原来是 IIS 相关的.我最终在 web.config 文件中设置了标题,现在 CORS 无需破解 routes.php 文件即可工作.

UPDATE: It turned out to be IIS related. I ended up setting the headers in the web.config file and now CORS works without hacking the routes.php file.

<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>

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

If you want to restrict access, you can add outbound rules:

      <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>

这篇关于Laravel 5.2 CORS,GET 不使用预检选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆