所以我有以下中间件:
<?php
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, PUT, DELETE, OPTIONS');
}
}
看起来很简单,它已注册:
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* @var array
*/
protected $middleware = [
// ...
\App\Http\Middleware\Cors::class,
];
/**
* The application's route middleware.
*
* @var array
*/
protected $routeMiddleware = [
'cors' => \App\Http\Middleware\Cors::class,
// ...
];
}
路由使用它:
Route::group([
'prefix' => 'api/v1/',
'middleware' => 'cors'
], function() {
// ...
});
然而控制台状态:
Fetch API cannot load http://examplesite.local/api/v1/blogs?_sort=id&_order=DESC&_start=0&_end=10. Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
最后我检查了这是在 Laravel 5.3 中设置 cors 的正确方法,所以除非我大错特错......
我可以在 chrome 的网络选项卡中单击 api 请求的链接,它会打开一个新选项卡,显示 api 的结果,这是一个 json 响应。
然而 javascript 假定 cors 未启用?
最佳答案
查看错误的最后一行,我猜您在服务器端缺少 content-type
header 。尝试将此行添加到您的标题中,看看它是否有效:
->header('Access-Control-Allow-Headers', 'Content-Type, X-Auth-Token, Origin');
你也可以看看 this回答。
关于php - 在 laravel 5.3 中设置 cors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42122902/