【问题标题】:Not able to add CORS for a particular route in Laravel 5无法在 Laravel 5 中为特定路线添加 CORS
【发布时间】:2023-03-28 23:50:01
【问题描述】:

我在我的应用程序中使用 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');

    } 

这是 CORS 类中的函数。

但是,当我返回 Blade 视图(例如 auth/login)时,我会在浏览器中获得纯 HTML 代码,而不是获得 HTML 的实际视图。

当我将“Content-Type”更改为 text/html 时,视图可以正常工作,但返回并接受 json 的 api 不起作用。

我哪里错了?

【问题讨论】:

  • ->header('Content-Type', 'application/json');。这是你的错误。该行告诉您的浏览器将内容显示为实际的 JSON 而不是 HTML 内容。去掉这行,就OK了
  • 但是,我还需要 api 的 application/json。
  • 你必须制作另一个中间件,并在一个包含所有 API 路由的组中使用它;

标签: php laravel cors laravel-5 blade


【解决方案1】:

您的问题是您告诉 Bowser 您正在发送 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,它通过检查接受的内容类型标头来做到这一点。见:https://github.com/laravel/framework/blob/5.0/src/Illuminate/Http/Request.php#L581

【讨论】:

    猜你喜欢
    • 2015-09-03
    • 2017-10-11
    • 2015-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 2022-12-05
    • 2015-12-11
    相关资源
    最近更新 更多