Laravel cors 'Access-Control-Allow-Origin' and 'Access-Control-Allow-Headers'

走远了吗. 提交于 2019-11-27 08:14:18

问题


I am new to Laravel.

I tried https://github.com/barryvdh/laravel-cors.

When I add

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

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

When I add

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

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?


回答1:


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

Run php artisan make:middleware ModifyHeadersMiddleware

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;
}

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



来源:https://stackoverflow.com/questions/37563350/laravel-cors-access-control-allow-origin-and-access-control-allow-headers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!