2017-07-08 265 views
2

我尝试使用Laravel(作为后端)和angularjs(作为前端)构建一个简单的api base应用程序。 在开始的时候,我遇到这个错误:CORS在共享主机上正常工作,但不在本地主机上

XMLHttpRequest cannot load http://127.0.0.1:8000/api/myroute . 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 ' is therefore not allowed access.

  • http://127.0.0.1:8000/api/myroute是我的路线得到一些数据,在Laravel定义为POST路线。

这虽然我已经添加了CORS中间件在我的路线(根据this sample)以这样的方式 一个Cors中间件:

public function handle($request, Closure $next) 
    { 
     return $next($request) 
      ->header('Access-Control-Allow-Origin', '*') 
      ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS') 
      ->header('Access-Control-Allow-Headers', 'x-requested-with, Content-Type, origin, authorization, accept, client-security-token'); 
    } 

和下面的代码是我$http代码,我送请求Angularjs:

$http({ 
    method: 'POST', 
    url: 'http://127.0.0.1:8000/api/myroute', 
    headers: { 
     'Content-Type': 'application/json' 
    } 
}).then(function (response) { 
    console.log(response); 
}, function (reject) { 
    console.log(reject); 
}); 

我应该补充这一点,当我上传我的项目的主机上,这一个Cors工作好吧! 我的问题只是http://localhost

我也试过在Firefox但结果是一样的,只是Firefox没有显示交叉原点错误,这是唯一的区别。

在这段时间,我无法在主机上开发我的项目,我需要在本地工作。 所以我需要帮助!

+0

奇怪的是你看到一个带有环回IP的URL,但原来是本地主机。你尝试过吗?url:'http:// localhost:8000/api/myroute','? –

+1

当我在本地开发(我在Windows上)时使用的另一项解决方法是将FQDN添加到我的主机文件中。该行看起来像这个'dev.somesite.local 127.0.0.1',然后我可以使用'url:'http://dev.somesite.local/api/myroute' –

+0

感谢您的意见,关于第一,是的!我尝试了两种,他们之间没有区别。关于第二条评论,我也是这样做的,但它与本地主机相同或127.0.0.1 –

回答

1

尝试下面的代码作为头添加到您的laravel的index.php文件:

header('Access-Control-Allow-Origin: *'); 
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS'); 
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization'); 

但要小心交叉origion!

相关问题