Laravel如何解决跨域请求被阻止

时间:2020-06-10 22:07:40

标签: laravel cors laravel-7

我想通过api读取pdf文件,但这给了我这个错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

我尝试过Ammar回答后,错误消息更改为

Access to fetch the resource from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

这是我的cors.php

<?php

return [

    'paths' => ['api/*'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'Access-Control-Allow-Origin'=> '*',

    'Access-Control-Allow-Headers'=> 'Origin, Content-Type',

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => false,

    'max_age' => false,

    'supports_credentials' => false,

];

如何解决此错误?

1 个答案:

答案 0 :(得分:0)

我认为PDF文件位于public文件夹中。 因此,您需要更改此行:

    'paths' => ['api/*'],

要这样:

    'paths' => ['*'],

因为公用文件夹路径没有前缀api前缀。

如果那不起作用。也许laravel没有将CORS相关的HTTP标头应用于文件的响应。因此,您需要配置Apache或Nginx。查看此问题:

https://github.com/fruitcake/laravel-cors/issues/163


更新

尝试将此配置添加到您的网络服务器:

<Directory /path/to/your/public/folder/>
        Header set Access-Control-Allow-Origin "*"
</Directory>