我是Laravel的新手,正在使用OAuth2.0密码授权进行一些Laravel 5.3 Passport项目。当我使用params卷曲API时,它会使用令牌进行响应。但是,在浏览器中,它需要端点应添加的额外安全性,因为我的请求来自localhost,而API位于我的VM中。这是错误:
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.
我知道问题是什么,但由于这是第三方应用程序,我不知道在哪里添加标题。
先谢谢专家。请帮忙。
答案 0 :(得分:97)
简单的答案是将Access-Control-Allow-Origin
标题设置为localhost
或*
。以下是我通常的做法:
创建一个名为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
或保持原样。
下一步是加载中间件。将以下行添加到$routeMiddleware
中的app/Http/Kernel.php
数组。
'cors' => \App\Http\Middleware\Cors::class,
最后一步是在要设置访问源头的路由上使用中间件。假设您正在讨论laravel 5.3中的新api路由,那么在app/Providers/RouteServiceProvider.php
函数内部可以mapApiRoutes()
执行此操作(您可以删除或注释函数的先前代码):
Route::group([
'middleware' => ['api', 'cors'],
'namespace' => $this->namespace,
'prefix' => 'api',
], function ($router) {
//Add you routes here, for example:
Route::apiResource('/posts','PostController');
});
答案 1 :(得分:18)
你也可以使用伟大的laravel-cors package by barryvdh。
安装软件包之后,获得所有路由的CORS支持的最简单方法是在Http / Kernel.php中添加这样的中间件:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Barryvdh\Cors\HandleCors::class,
];
如果您不想在所有路由上获得CORS支持,则应为/oauth/token
创建新的OPTIONS路由,并仅将cors中间件添加到该路由。
答案 2 :(得分:15)
简单的答案是将Access-Control-Allow-Origin标头设置为localhost或*。这是我通常的操作方式:
将以下代码添加到bootstrap / app.php:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');
答案 3 :(得分:4)
对于那些没有解决在App\Http\Kernel
中设置路由中间件的问题的人,请尝试设置全局中间件。在App\Http\Middleware\Cors
中:
public function handle($request, Closure $next)
{
return $next($request)->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods','GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS')
->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
}
在App\Http\Kernel
中:
protected $middleware = [
...
\App\Http\Middleware\Cors::class,
];
答案 4 :(得分:3)
之后
https://github.com/fruitcake/laravel-cors
我必须按如下所示更改cors.php文件
* Sets the Access-Control-Allow-Credentials header.
*/
'supports_credentials' => true,
答案 5 :(得分:2)
小心,你不能修改预检。 此外,浏览器(至少是chrome)删除了“授权”标题......这会导致根据路由设计可能出现的一些问题。例如,预检永远不会进入护照路由表,因为它没有带令牌的标题。
如果您正在设计一个带有options方法实现的文件,您必须在路由文件web.php中定义一个(或多个)“陷阱”路由,以便preflght(没有头部授权)可以解析请求并获取相应的CORS头。 因为默认情况下它们无法返回中间件200,所以它们必须在原始请求中添加标头。
答案 6 :(得分:1)
工作解决方案
第1步:创建Cors中间件
php artisan make:middleware Cors
第2步:在处理函数内部的Cors中间件中设置标头
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
第3步:在 app / Http / Kernel.php
中添加Cors类protected $routeMiddleware = [
....
'cors' => \App\Http\Middleware\Cors::class,
];
第4步:替换 app / providers / routeServiceProvider.php
中的mapApiRoutesRoute::prefix('api')
->middleware(['api', 'cors'])
->namespace($this->namespace)
->group(base_path('routes/api.php'));
第5步:在 routes / api.php
中添加您的路由Route::post('example', 'controllerName@functionName')->name('example');
答案 7 :(得分:1)
如果由于某种原因它仍然无法正常工作。 Laravel的首选 任何应用程序的第二个选择
首选:
如上例所示,我们创建中间件
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, PATCH, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range');
}
仔细查看标题->header('Access-Control-Allow-Headers',
中的数据量
第三步,在$routeMiddleware
的{{1}}数组中添加中间件
app/Http/Kernel.php
第二个选项:
打开您域的nginx.conf设置。
protected $routeMiddleware = [
....
'cors' => \App\Http\Middleware\Cors::class,
];
在服务器设置服务器 sudo nano /etc/nginx/sites-enabled/your-domain.conf
内,请添加以下代码:
{ listen 80; .... }
答案 8 :(得分:0)
只需将其添加到您的视图中:
<rule name="aaa" stopProcessing="true">
<match url=".*" />
<action type="Redirect" url="http://example.com/index.php/{R:0}" />
<conditions>
<add input="{HTTP_HOST}" pattern="example.com/index.php" negate="true" />
</conditions>
</rule>
答案 9 :(得分:0)
在App / Http / Middleware中创建一个Cors.php文件并将其粘贴到其中。 ☑
<?php
namespace App\Http\Middleware;
use Closure;
class Cors { 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()->json('OK',200,$headers);
}
$response = $next($request);
foreach ($headers as $key => $value) {
$response->header($key, $value);
}
return $response;
} }
然后在“ Trust Proxies :: Class”行之后,在您的Kernel.php中添加此行。
\App\Http\Middleware\Cors::class,
就这样,您已经允许了所有Cors标头。 ☑
答案 10 :(得分:0)
只需将其添加到您的代码控制器中
return response()->json(compact('token'))->header("Access-Control-Allow-Origin", "*");
答案 11 :(得分:0)
我使用的是Laravel 6,虽然评分最高的答案最终对我有用,但我不得不稍作调整。
mapApiRoutes()
中的app/Providers/RouteServiceProvider.php
函数现在看起来像这样-
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
因此,我只是将cors
添加到api
中$middlewareGroups
下的app/Http/Kernel.php
数组中,就解决了我的所有麻烦。
protected $middlewareGroups = [
...
'api' => [
'throttle:60,1',
'bindings',
'cors',
],
];
答案 12 :(得分:0)
如果您已应用CORS中间件,但仍无法正常工作,请尝试此操作。
如果您的API的路由为:
Route::post("foo", "MyController"})->middleware("cors");
然后您需要对其进行更改以允许使用OPTIONS方法:
Route::match(['post', 'options'], "foo", "MyController")->middleware("cors");
答案 13 :(得分:0)
将Access-Control-Allow-Origin
标头添加到localhost or *.
的几个步骤
第1步:创建Cors中间件:
php artisan make:middleware Cors
第2步:像这样在Cors中间件中设置标头
public function handle($request, Closure $next)
{
$response = $next($request);
$response->headers->set('Access-Control-Allow-Origin' , '*');
$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
return $response;
}
第3步:我们需要在app/Http/Kernel.php
中添加Cors类
protected $middleware = [
....
\App\Http\Middleware\Cors::class,
];
这里不需要检查任何中间件
因为我们在$middleware
的{{1}}中添加了Cors类
答案 14 :(得分:0)
我正在使用 Laravel 8 并且刚刚安装了 fruitcake/laravel-cors
并在 app/Http/Kernel.php
中使用它,例如:
protected $middleware = [
....
\Fruitcake\Cors\HandleCors::class,
];
注意: 像我一样将它添加到数组的末尾