【问题标题】:Cross-Origin Request Blocked Angular JS Put request跨域请求被阻止 Angular JS Put 请求
【发布时间】:2014-10-24 06:54:18
【问题描述】:

我正在使用 Yii 框架为服务器端和 Angular JS 为客户端开发一个 REST-ful 应用程序

我正在使用restfulyii扩展来生成api

:我在发送 PUT 请求时遇到了问题。

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ..... This can be fixed by moving the resource to the same domain or enabling CORS.

但它适用于 post + get 请求

我看到了不同的解决方案,但都没有奏效。

我试着把那些放在服务器端

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");
header("Access-Control-Max-Age: 1000");

并尝试将此代码放入 Angular js 模块中:

$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];

我也试着把

 $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

请求转化为OPTIONS请求 来自服务器的响应如下:

Access-Control-Allow-Headers:x-requested-with, Content-Type, origin, authorization, accept, client-security-token 
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS Access-Control-Allow-
Origin:http://localhost:8383
 Access-Control-Max-Age:1000
 Connection:close
 Content-Type:text/html Date:Fri, 24 Oct 2014 06:49:32 GMT
 Server:Apache/2.4.7 (Win32) OpenSSL/1.0.1e PHP/5.5.9 X-Powered-By:PHP/5.5.9

【问题讨论】:

  • 尝试将确切的域名而不是 * 放入 header("Access-Control-Allow-Origin: *");
  • 但是当我使用邮递员扩展发送确切的请求时,它可以工作!
  • 你是如何加载你的 Angular 网站的?你使用的是 file:// 还是 http:// 协议?

标签: javascript angularjs yii


【解决方案1】:

我的所有使用 restangular 的休息控制器都有一个基本控制器,它具有以下事件。

public function restEvents()
{
    $this->onRest('req.cors.access.control.allow.origin', function() {
        return ['*']; //List of sites allowed to make CORS requests 
    });

    $this->onRest('req.cors.access.control.allow.methods', function() {
        return ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']; //List of allowed http methods (verbs) 
    });

    $this->onRest('req.auth.cors', function ($allowed_origins) {
        if (in_array('*', $allowed_origins)) {
            return true;
        }
        if((isset($_SERVER['HTTP_ORIGIN'])) && (( array_search($_SERVER['HTTP_ORIGIN'], $allowed_origins)) !== false )) {
            return true;
        }
        return false;   
    });

    $this->onRest('req.cors.access.control.allow.headers', function($application_id) {
        return ["X_{$application_id}_CORS", "Content-Type", "Authorization", "X_REST_REQUEST"];
    });

}

客户端我正在使用带有以下选项的restangular:

RestangularProvider.setDefaultHttpFields({withCredentials: true}); RestangularProvider.setDefaultHeaders({X_REST_CORS: 'Yes'}); RestangularProvider.setDefaultHttpFields({cache: false});

我希望这会有所帮助....

【讨论】:

    猜你喜欢
    • 2023-03-03
    • 2016-05-19
    • 2018-10-07
    • 2019-02-22
    • 2015-04-24
    • 2017-09-12
    • 2019-11-04
    • 2017-02-06
    • 2022-02-16
    相关资源
    最近更新 更多