无法使用 $http 从 AngularJs 向 Web API 发送 DELETE

Unable to sent DELETE to Web API from AngularJs with $http

我的 Web API 2 解决方案中有一个 oData 控制器,我试图从我的 angularJs 应用程序调用删除操作。我试过:

$http({
    method: 'DELETE',
    url: "http://localhost:52389/odata/Bears('" + $scope.itemKey + "')",
    headers: { 'Content-Type': 'application/json' }
}).then(function successCallback(response) {
    console.log('success', response);
}, function errorCallback(response) {
    console.log('error', response);
});

在 fiddler 中,这似乎向 API 发送了一个 OPTIONS 请求。在 fiddler 中检查发送的请求,我可以看到这是发送的内容:

OPTIONS http://localhost:52389/odata/Bears('1') HTTP/1.1
Host: localhost:52389
Connection: keep-alive
Access-Control-Request-Method: DELETE
Origin: http://localhost
X-FirePHP-Version: 0.0.6
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36
Access-Control-Request-Headers: accept
Accept: */*
Referer: http://localhost/?id=places
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6

如果我在 fiddler 中更改第一行:

OPTIONS http://localhost:52389/odata/Bears('1') HTTP/1.1

至:

DELETE http://localhost:52389/odata/Bears('1') HTTP/1.1

那么这行得通。如何从 angularJs 获取方法 'DELETE'?

已发送 OPTIONS,因为您正在发送跨源请求。服务器需要首先同意这一点,因此是第一个 OPTIONS 请求。

如果OPTIONS后没有发送DELETE,则服务器的响应很可能是否定的,这意味着您需要在服务器上配置CORS。