【发布时间】:2021-02-16 22:17:44
【问题描述】:
我正在尝试从 Angular 访问日志文件 URL,但它显示以下错误:
Access to XMLHttpRequest at 'https://myurl.com/storage/rmlogs/MyFileNameDetail.log' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
所有 API 请求都运行良好,错误仅针对文件请求。我的文件存储在rmlogs 目录中,该目录位于storage/app/public/rmlogs 中,并且链接到公用文件夹。
API 代码库是 Laravel,文件存储在 storage 目录中。我可以通过浏览器和 Postman 访问该文件。由于该 URL 是公开可用的,因此它不需要我为其他 API 请求传递的身份验证令牌。
我有cors.php的配置文件如下:
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
并且有一个Cors.php 中间件,如下所示:
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
【问题讨论】:
-
那是一个错字。都是
rmlogs。但它不起作用 -
你需要允许
http://localhost:4200的交叉放'paths' => ['api/*','http://localhost:4200'], -
由于它访问的是文件而不是路由,我认为您可能需要在添加 CORS 标头的
rmlogs文件夹中添加.htaccess -
@KamleshPaul —
paths是本地系统上要应用 CORS 标头的文件,而不是允许的来源。