在Laravel 5.3 Passport中添加Access-Control-Allow-Origin标头响应 [英] Adding Access-Control-Allow-Origin header response in Laravel 5.3 Passport

查看:86
本文介绍了在Laravel 5.3 Passport中添加Access-Control-Allow-Origin标头响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Laravel的新手,正在做一些具有OAuth2.0密码授予功能的Laravel 5.3 Passport项目.当我使用参数卷曲API时,它将以令牌响应.但是,在浏览器中,它需要端点添加的其他安全性,因为当API位于我的VM中时,我的请求来自本地主机.这是错误:

I'm new to Laravel and am doing some Laravel 5.3 Passport project with OAuth2.0 password grant. When I curl the API with the params it responds with token. However, in browser it needs an additional security that the endpoint should add because my request is coming from localhost while the API is located in my VM. Here's the error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 400.

我知道问题出在哪里,但我不知道在哪里包含该标头,因为这是第三方应用程序.

I know what the issue is but I don't know where to put to include that header since this is a third party app.

预先感谢您的专家.请帮忙.

Thank you in advance experts. Please help.

推荐答案

简单的答案是将Access-Control-Allow-Origin标头设置为localhost*.这是我通常的操作方式:

The simple answer is to set the Access-Control-Allow-Origin header to localhost or *. Here's how I usually do it:

创建一个名为Cors的简单中间件:

Create a simple middleware called Cors:

php artisan make:middleware Cors

将以下代码添加到app/Http/Middleware/Cors.php:

public function handle($request, Closure $next)
{
    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}

您可以将*替换为localhost或保持原样.

You can replace the * with localhost or keep it as it is.

下一步是加载中间件.将以下行添加到app/Http/Kernel.php中的$routeMiddleware数组中.

Next step is to load the middleware. Add the following line to the $routeMiddleware array in app/Http/Kernel.php.

'cors' => \App\Http\Middleware\Cors::class, 

最后一步是在要设置访问源标头的路由上使用中间件.假设您正在谈论的是laravel 5.3中的新api路由,那么在mapApiRoutes()函数内部的位置是app/Providers/RouteServiceProvider.php(您可以删除或注释该函数的先前代码):

And the final step is to use the middleware on the routes to which you want to set the access origin headers. Assuming you are talking about the new api routes in laravel 5.3, the place to do it is app/Providers/RouteServiceProvider.php, inside the mapApiRoutes() function (you can remove or comment the previous code of the function):

    Route::group([
        'middleware' => ['api', 'cors'],
        'namespace' => $this->namespace,
        'prefix' => 'api',
    ], function ($router) {
         //Add you routes here, for example:
         Route::apiResource('/posts','PostController');
    });

这篇关于在Laravel 5.3 Passport中添加Access-Control-Allow-Origin标头响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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