如何在Laravel Lumen 5.5.2中以“ angular4”作为前端为OPTIONS预检请求添加CORS标头

时间:2019-03-24 06:37:02

标签: php angular laravel lumen

我在机器上的localhost \ 8080上运行laravel lumen php frameowrk 5.5.2。在localhost \ 4200上本地运行angular4前端。当我运行应用程序时,我可以通过angular连接到一些Laravel API并获取数据,也可以对这些API进行更改。但是,当我尝试通过前端连接到Laravel中的其他一些api时,在浏览器控制台“从源{http://localhost:8080/ABC'访问XMLHttpRequest在http://localhost:4200”处出现了此错误,被CORS政策阻止:对预检请求的响应未通过访问控制检查:所请求的资源上没有“ Access-Control-Allow-Origin”标头。“

因此,我参考了此链接,并在Laravel后端服务器代码上进行了相应的更改,如下所述: https://gist.github.com/danharper/06d2386f0b826b669552#file-usage-md

但是,当我通过角度连接到Laravel API时,现在出现此错误: “从源'http://localhost:8080/ABC'到'http://localhost:4200'的XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:它没有HTTP正常状态。” < / p>

我还必须对前端角度编码进行任何更改吗? 由于CORS的阻塞,我无法前进...任何帮助将不胜感激。

这是我在Laravel中的CorsMiddleware.php文件:

使用闭包;

CorsMiddleware类 {

public function handle($request, Closure $next)
{

    $response = $next($request);
    $response->header('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, 
    PATCH, DELETE');
    $response->header('Access-Control-Allow-Headers', $request- 
    >header('Access-Control-Request-Headers'));
    $response->header('Access-Control-Allow-Origin', '*');
    return $response;    
}

}

这是我在Laravel中的CatchAllOptionsRequestsProvider.php文件:

/ ** *如果传入请求是OPTIONS请求 *我们将为请求的路线注册一个处理程序 * /

CatchAllOptionsRequestsProvider类扩展了ServiceProvider {

public function register()
{
    $request = app('request');

    if ($request->isMethod('OPTIONS'))
    {
       app()->options($request->path(), function() { return response('', 
       200); 
    });
}

}

这是我的app.php文件,我在其中注册了提供程序和Cors中间件:

$ app-> register(App \ Providers \ CatchAllOptionsRequestsProvider :: class);

$ app-> routeMiddleware(['auth'=> App \ Http \ Middleware \ Authenticate :: class,]);

$ app->中间件([App \ Http \ Middleware \ CorsMiddleware :: class]);

1 个答案:

答案 0 :(得分:0)

执行以下操作:

1。创建中间件

<?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)
    {
        $headers = [
            'Access-Control-Allow-Origin'      => '*',
            'Access-Control-Allow-Methods'     => 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Max-Age'           => '86400',
            'Access-Control-Allow-Headers'     => 'Content-Type, Authorization, X-Requested-With'
        ];

        if ($request->isMethod('OPTIONS'))
        {
            return response()->json('{"method":"OPTIONS"}', 200, $headers);
        }

        $response = $next($request);
        foreach($headers as $key => $value)
        {
            $response->header($key, $value);
        }

        return $response;
    }
}

2。将中间件添加到app / Http / kernel.php(用于laravel)

protected $middleware  = [
//...... other middlewares
\App\Http\Middleware\CorsMiddleware::class
];

对于流明,请在bootstrap / app.php中完成

 $app->middleware([
      App\Http\Middleware\CorsMiddleware::class
 ]);

完成!