访问控制允许来源

访问控制允许来源

本文介绍了Laravel的“访问控制允许来源"和“访问控制允许标题"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Laravel的新手.

I am new to Laravel.

我尝试了 https://github.com/barryvdh/laravel-cors .

当我添加

header('Access-Control-Allow-Origin: *');

在我的public/index.php中,它没有在响应中添加Content-Type.

in my public/index.php, it does not add the Content-Type in the response.

当我添加

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, Content-Type');

它不添加Access-Control-Allow-Origin.

It does not add Access-Control-Allow-Origin.

我对在互联网上找到的所有各种解决方案感到非常困惑.我应该怎么做?

I am very confused by all various solutions I find on internet.How exactly should I go about this?

推荐答案

您可以创建一个新的中间件并将标头添加到响应中:

You can create a new middleware and add the headers to the response:

运行php artisan make:middleware ModifyHeadersMiddleware

打开文件 ModifyHeadersMiddleware 并修改handle()方法:

Open the file ModifyHeadersMiddleware and modify the handle() method:

public function handle( $request, Closure $next )
{
    $response = $next( $request );
    $response->header( 'Access-Control-Allow-Origin', '*' );
    $response->header( 'Access-Control-Allow-Headers', 'Origin, Content-Type' );

    return $response;
}

打开 app/Http/Kernel.php ,然后在protected $middleware数组中添加 ModifyHeadersMiddleware 类.

Open app/Http/Kernel.php and in the protected $middleware array add the ModifyHeadersMiddleware class.

这篇关于Laravel的“访问控制允许来源"和“访问控制允许标题"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 10:07