【问题标题】:$http.delete throwing error in angularJS$http.delete 在 angularJS 中抛出错误
【发布时间】:2015-05-26 07:10:39
【问题描述】:

我正在像这样对Delete 方法进行 api 调用 -

$http.delete('http://localhost:45467/api/v1/proddetails/' + prodId, null )
    .success(function (data, status, headers, config) {
        if(data.status == "200")
        {
            console.log('data deleted');
        }
        deferred.resolve(data);
    })
    .error(function (data, status, headers, config) {
        console.log("some error occurred");
        deferred.reject(data);
    });

删除端点如下所示 -

[HttpDelete]
public HttpResponseMessage Delete(int productId)

当我运行它并查看 Chrome 控制台时,我看到了这个错误 -

OPTIONS http://localhost:45467/api/v1/proddetails/34 
(index):1 XMLHttpRequest cannot load   
http://localhost:45467/api/v1/proddetails/34. No 'Access-Control-Allow-  
Origin' header is present on the requested resource. Origin 
'http://localhost:5100' is therefore not allowed access. The response had 
HTTP status code 405.

似乎无法弄清楚这里出了什么问题。其他 Get 和 Post 请求工作正常。如何解决这个问题?

注意1:我已经启用了CORS -

[EnableCors(origins: "*", headers: "*", methods: "*")]

注意2:我正在使用interceptors 为每个请求添加一个身份验证令牌。我不确定这是否会导致任何问题。

注意 3:这是我在 asp.net webapiconfig 文件中定义路由的方式 -

config.Routes.MapHttpRoute(
            name: "ProdApi",
            routeTemplate: "api/v1/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

提前致谢。

【问题讨论】:

  • 看起来像服务器端的问题stackoverflow.com/a/15619435/2435473
  • 我加了,还是没用。
  • 我不确定发生了什么。如果有人需要任何信息来挖掘这个,我可以提供。但是这个问题正在奇怪的程度。
  • 您是否尝试从本地 chrome 扩展邮递员中删除记录?
  • 我现在试了,它说-请求的资源不支持http方法'DELETE'

标签: angularjs asp.net-mvc asp.net-web-api xmlhttprequest


【解决方案1】:

我终于弄清楚了问题所在。其实这篇文章很有帮助- PUT and Delete not working with ASP.NET WebAPI and Database on Windows Azure

我只需要将 productId 参数替换为 id - 它存在于 webapiconfig 配置中。我不确定为什么会这样。理想情况下,我应该能够为参数输入任何名称,并且不受我在路由中输入的内容的约束。希望有人能解释一下。

【讨论】:

    【解决方案2】:

    您正在向与您的页面所在的域不同的域发出 HTTP 请求。出于安全原因,浏览器正在阻止它。

    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    

    This 问题解释了如何使DELETE http 请求与asp.net-web-api 一起使用。

    【讨论】:

    • 我启用了 CORS。就像我说的,GET 和 POST 请求工作正常。
    • 在 Chrome 给你的错误中,我们可以看到 No 'Access-Control-Allow-Origin' header 你的 CORS 配置可能有问题。您确定包含正确的标题吗?
    • 已在 CORS 中设置方法:"*"。
    • 您可能需要明确指定允许的方法GET, POST, PUT, DELETE, OPTIONS
    • 查看这个问题了解更多详情:stackoverflow.com/questions/12521499/…
    【解决方案3】:

    $http.delete() 更改为$http.del()

    【讨论】:

      猜你喜欢
      • 2013-04-07
      • 2014-03-18
      • 1970-01-01
      • 2013-03-24
      • 1970-01-01
      • 2015-11-07
      • 1970-01-01
      • 1970-01-01
      • 2016-02-11
      相关资源
      最近更新 更多