它工作得很好,但有一段时间我已经停止了这个项目的工作。我正在向我的服务器发送删除请求,它给了我Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://abc.dev/users/users/18. (Reason: CORS preflight channel did not succeed).(unknown)
API是用Yii框架编写的。我对firefox使用了CORS
扩展名,我的GET, POST
方法工作得非常好,但我的DELETE
方法似乎卡住了。
我的控制器
$scope.delete = function (id)
{
if (confirm("Are you sure you want to delete the user") === true) {
$http({
method: 'DELETE',
url: 'http://abc.dev/users/users/' + id,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function (data) {
$scope.singleuser = data;
console.log("function single user is processed");
$scope.user(); //call the function to reload
})
.error(function (data) {
console.log('error');
});
}
我的后端APi删除功能
public function actionDelete() {
switch ($_GET['model']) {
// Load the respective model
case 'users':
$model = User::model()->findByPk($_GET['id']);
break;
default:
$this->_sendResponse(501, sprintf('Error: Mode <b>delete</b> is not implemented for model <b>%s</b>', $_GET['model']));
Yii::app()->end();
}
// Was a model found? If not, raise an error
if ($model === null)
$this->_sendResponse(400, sprintf("Error: Didn't find any model <b>%s</b> with ID <b>%s</b>.", $_GET['model'], $_GET['id']));
// Delete the model
$num = $model->delete();
if ($num > 0)
$this->_sendResponse(200, $num); //this is the only way to work with backbone
else
$this->_sendResponse(500, sprintf("Error: Couldn't delete model <b>%s</b> with ID <b>%s</b>.", $_GET['model'], $_GET['id']));
}
}
答案 0 :(得分:1)
您正在执行跨源请求,大多数浏览器在检查Access-Control-Allow-Origin的实际请求之前发送OPTION请求。如果当前域是允许的,则执行请求。
答案 1 :(得分:0)
这是服务器端问题。为了安全起见并节省服务器负载,Web服务器默认不允许跨源请求。
由于您使用的是localhost,因此不允许。它应该在现场网站上运行得很好。但是,如果您想允许Cross origin,则必须根据您使用的内容在服务器上的NGINX / Apache .conf文件中进行更改。
例如: 对于Nginx,您需要在请求中添加几个标题
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With';
答案 2 :(得分:0)
这是服务器端问题此文档解决了我的问题https://gist.github.com/sourcec0de/4237402
。