无法为 Laravel 5 中的特定路由添加 CORS
Not able to add CORS for a particular route in Laravel 5
我正在为我的应用程序使用 Laravel 5 并设置我使用 CORS 中间件的内容类型,如下所示。
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Credentials', 'true')
->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With')
->header('Content-Type', 'application/json');
}
这是 Class CORS 中的函数。
但是,当我 return Blade 视图时,例如 auth/login
,我在浏览器中得到一个普通的 HTML 代码,而不是 [=25] 的实际视图=].
当我将 'Content-Type' 更改为 text/html 时,视图有效,但 return 和接受 json 的 API 无效。
我哪里错了?
您的问题是您告诉浏览器您正在发送 json,但实际上发送的是 HTML。
您可以使用以下方法解决此问题。
public function handle($request, Closure $next)
{
$return = $next($request)
->header('Access-Control-Allow-Credentials', 'true')
->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With');
if ($request->wantsJson())
{
$return->header('Content-Type', 'application/json');
}
return $return;
}
通过使用 $request->wantsJson()
函数,您可以判断当前请求是否要求接收 json,它通过检查已接受的 content-type header。参见:https://github.com/laravel/framework/blob/5.0/src/Illuminate/Http/Request.php#L581
我正在为我的应用程序使用 Laravel 5 并设置我使用 CORS 中间件的内容类型,如下所示。
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Credentials', 'true')
->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With')
->header('Content-Type', 'application/json');
}
这是 Class CORS 中的函数。
但是,当我 return Blade 视图时,例如 auth/login
,我在浏览器中得到一个普通的 HTML 代码,而不是 [=25] 的实际视图=].
当我将 'Content-Type' 更改为 text/html 时,视图有效,但 return 和接受 json 的 API 无效。
我哪里错了?
您的问题是您告诉浏览器您正在发送 json,但实际上发送的是 HTML。
您可以使用以下方法解决此问题。
public function handle($request, Closure $next)
{
$return = $next($request)
->header('Access-Control-Allow-Credentials', 'true')
->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With');
if ($request->wantsJson())
{
$return->header('Content-Type', 'application/json');
}
return $return;
}
通过使用 $request->wantsJson()
函数,您可以判断当前请求是否要求接收 json,它通过检查已接受的 content-type header。参见:https://github.com/laravel/framework/blob/5.0/src/Illuminate/Http/Request.php#L581