laravel核心

跨域踩坑

2017-07-25  本文已影响103人  王宝花

跨域问题

在当前域名下访问其它域名下资源时,会出现这个问题。跨域详细信息

错误:

:1111/#/login:1 XMLHttpRequest cannot load http://employment.dev/api/login. 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:1111' is therefore not allowed access. The response had HTTP status code 403.

解决方式

  1. 需要后端支持。如果你使用的laravel,推荐使用barryvdh/laravel-cors这个包,只需要对需要跨域的路由加上这个中间件即可。
  2. 如果你使用dingo API组件的话,你需要在config/api.php中进行配置中间件。
...
'middleware' => [
        'cors' => \Barryvdh\Cors\HandleCors::class,
    ],
...

然后在路由中使用即可:

$api->version('v1', [ 'middleware' => 'cors'], function ($api) {
...
});
上一篇 下一篇

猜你喜欢

热点阅读