我尝试使用 Laravel(作为后端)和 angularjs(作为前端)构建一个简单的 api 基础应用程序。 一开始,我遇到了这个错误:
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');
}
下面的代码是我在 Angularjs 中发送请求的 $http
代码:
$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 没有显示跨源错误,这是唯一的区别。
这段时间我无法在主机上开发我的项目,我需要在本地工作。 所以我需要帮助!
最佳答案
尝试将以下代码作为 header 添加到 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');
但要小心跨源!
关于php - CORS 在共享主机上正常工作,但在本地主机上不正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44991047/