可怕的CORS错误:
跨源请求已阻止:同源策略禁止在http:// localhost/mysite/api/test中读取远程资源.(原因:缺少CORS标题'Access-Control-Allow-Origin').
Laravel路线:
$router->group(['prefix' => 'api', 'middleware' => 'cors'], function ($router) {
$router->get('/test', 'MyController@myMethod');
});
Run Code Online (Sandbox Code Playgroud)
Laravel Cors Middlware:
public function handle($request, Closure $next)
{
header('Access-Control-Allow-Origin: *');
// ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization'
];
if ($request->getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return Response::make('OK', 200, $headers);
}
$response = $next($request);
foreach ($headers as $key => $value) …Run Code Online (Sandbox Code Playgroud) 我希望在我的 laravel 中允许两个用于 CORS 的域能够在本地和服务器上使用它,因此我不想将我的应用程序暴露给任何域。这就是我现在所拥有的
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', 'http://localhost:4200')
// ->header('Access-Control-Allow-Origin', 'http://api.example.com')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE')
->header('Access-Control-Allow-Headers', 'Content-Type');
}
Run Code Online (Sandbox Code Playgroud)
我既不能像我评论的那样,也不能像数组那样做
当我尝试 POST 到给定的 url 时,当前收到一条错误消息。GET 在同一个域上工作正常,这是我的错误:
CORS 策略阻止了在 ' http://localhost:8000/api/users/login '处访问 XMLHttpRequest来自源 ' http://localhost:8080 ' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否请求的资源上存在“Access-Control-Allow-Origin”标头。
我发现无数问题记录了同样的问题,所有这些问题都包含修改我的 Cors 中间件的变体。
目前我的 CORS 中间件如下所示:
class Cors
{
public function handle($request, Closure $next)
{
if ($request->isMethod('OPTIONS')) {
$response = Response::make();
} else {
$response = $next($request);
}
return $response
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
}
}
Run Code Online (Sandbox Code Playgroud)
错误指出 No 'Access-Control-Allow-Origin' 我相信我->header('Access-Control-Allow-Origin', '*')应该处理它,因为 * 是我理解的通配符。我错过了这里有什么不同的问题吗?Stack 是 Laravel 后端,VueJS 前端使用 Axios 进行 HTTP …
我有一个 Laravel 应用程序,它托管在 Apache 上,但现在已迁移到 nginx 上。我是 nginx 的新手。
在 Apache 上,我的 htaccess 中有这个:
<IfModule mod_headers.c>
<FilesMatch "\.(svg|ttf|otf|eot|woff|woff2)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
新的托管提供商不允许自定义 nginx 配置。
是否可以在 Laravel 应用程序 PHP 代码中为静态字体文件(扩展名:svg|ttf|otf|eot|woff|woff2)添加 Cors 标头(Access-Control-Allow-Origin: *)?我尝试(在 Laravel 5.3 Passport 中添加 Access-Control-Allow-Origin 标头响应)没有成功,我的猜测是静态文件不是该代码段的目标。你确认吗?
有没有办法在我的应用程序的 PHP 代码中实现此目的?
谢谢