php - CORS 在共享主机上正常工作,但在本地主机上不正常

标签 php angularjs laravel cors

我尝试使用 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/

相关文章:

php - Magento 订单被收取两次费用

javascript - Angular Modal 仅适用于 Index.html

php - 带有 MySQL 数据库的 PHP Yii 框架上的应用程序是否可以处理 20,000 名员工的 ERP 解决方案?

javascript - 防止用户多次单击 'like' 的最佳方法

php - 编辑记录 PHP 表单

angularjs - Sinatra + Angularjs 路由

javascript - Angularjs foreach 只返回一个对象

php - 拉拉维尔 : email send multiples times to one user

php - Laravel 不从地址发送

php - Gulp 与 Laravel Elixir 抛出 events.js :141 unhandled 'error' event