gpt4 book ai didi

javascript - 跨源请求阻止 Angular JS Put 请求

转载 作者:行者123 更新时间:2023-12-03 16:27:29 26 4
gpt4 key购买 nike

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

我正在使用 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

最佳答案

我有一个用于所有使用 restangular 的其余 Controller 的基本 Controller ,它具有以下事件。

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

希望对您有所帮助....

关于javascript - 跨源请求阻止 Angular JS Put 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26542898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com