CORS在共享主机上正常工作,但在localhost中没有

时间:2017-07-08 21:50:15

标签: php angularjs laravel cors

我尝试使用Laravel(作为后端)和angularjs(作为前端)构建一个简单的api基础应用程序。 一开始,我遇到了这个错误:

  

XMLHttpRequest无法加载http://127.0.0.1:8000/api/myroute。响应   预检请求未通过访问控制检查:否   请求中存在“Access-Control-Allow-Origin”标头   资源。因此,不允许原点“http://localhost”访问。

  • http://127.0.0.1:8000/api/myroute是获取一些数据的途径,在Laravel中定义为POST路径。

那时我已经以这种方式在我的路线上添加了CORS中间件(根据this sample): Cors Middleware:

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没有显示Cross Origin Error,这是唯一的区别。

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

1 个答案:

答案 0 :(得分: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');

但要注意交叉原点!

相关问题