没有'Access-Control-Allow-Origin'标头-Laravel 5.4 [英] No 'Access-Control-Allow-Origin' header - Laravel 5.4

查看:91
本文介绍了没有'Access-Control-Allow-Origin'标头-Laravel 5.4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

XMLHttpRequest无法加载 http://myapi/api/rating .对预检请求的响应未通过访问控制检查:在所请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许访问来源" http://localhost:8104 .响应的HTTP状态码为403.

XMLHttpRequest cannot load http://myapi/api/rating. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8104' is therefore not allowed access. The response had HTTP status code 403.

我不知道为什么我不能提出CORS请求.我已经在此处安装了中间件,并将其添加到了全局http内核中,但仍然无法正常工作.尝试创建给定stackoverflow建议的自定义中间件,但这也行不通.还尝试添加路由组.最后,我尝试在请求操作中手动设置响应头.我真的很困-感谢您的帮助!

I can't figure out why I can't make CORS requests. I've install the middleware here, added it to the global http kernel, but it still doesn't work. Tried to create a custom middleware given stackoverflow suggestions but that also did not work. Also tried adding a Route group. Lastly, I tried setting the response headers manually in the request action. I'm really stuck - help is appreciated!

请参见代码: https://gist.github.com/KerryRitter/0d7ababb7b9eb8d54f0ae55add9704a1

推荐答案

如果您使用的是Laravel 5.5& Laravel 5.x并面临与No 'Access-Control-Allow-Origin' header is present on the requested resource类似的问题.只需使用以下软件包并配置您的系统即可.

If you are using Laravel 5.5 & Laravel 5.x and facing same problem like No 'Access-Control-Allow-Origin' header is present on the requested resource. Just use following package and config your system.

第1步:

composer require barryvdh/laravel-cors

第2步

您还需要将Cors\ServiceProvider添加到您的config/app.php提供程序数组:

You also need to add Cors\ServiceProvider to your config/app.php providers array:

FruitCake\Cors\CorsServiceProvider::class,

要允许所有路径使用CORS,请在app/Http/Kernel.php类的$middleware属性中添加HandleCors中间件:

To allow CORS for all your routes, add the HandleCors middleware in the $middleware property of app/Http/Kernel.php class:

供全球使用:

protected $middleware = [
    // ...
    \Fruitcake\Cors\HandleCors::class,
];

对于中间件使用:

protected $middlewareGroups = [
   'web' => [
       // ...
   ],

   'api' => [
        // ...
        \Fruitcake\Cors\HandleCors::class,
    ],
];

第3步

安装完成后,请运行以下命令来发布供应商文件.

Once your installation completed run below command to publish the vendor files.

php artisan vendor:publish --provider="Fruitcake\Cors\ServiceProvider"

希望这个答案可以帮助面临与我自己相同的问题的人.

Hope this answer helps someone facing the same problem as myself.

这篇关于没有'Access-Control-Allow-Origin'标头-Laravel 5.4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆