跨域请求被阻止 Angular JS Put 请求

3
我正在使用Yii框架作为服务器端,Angular JS作为客户端,开发一款RESTful应用程序。 我使用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: ");中放置确切的域名,而不是 - Vecnas
但是当我使用Postman扩展发送完全相同的请求时,它可以正常工作! - Hanihh
你是如何加载你的 Angular 网站的?你使用的是 file:// 还是 http:// 协议? - tslater
1个回答

0

我有一个基础控制器,用于所有使用restangular的rest控制器,其中包含以下事件。

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});

希望这可以帮到你....


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接