【问题标题】:Add parameters to query string when using PUT method with Angular's $http使用带有 Angular 的 $http 的 PUT 方法时向查询字符串添加参数
【发布时间】:2015-10-12 21:46:27
【问题描述】:

我正在使用 Angular 的 $http 服务来发出 web api 请求。当我使用 GET 方法时,两个参数值被添加到查询字符串中:

// http://foo.com/api/test?heroId=123&power=Death+ray
$http.get("/api/test", {
   params: { heroId: 123, power : "Death ray" }
})

但是,当我使用 PUT 方法时,参数被 JSON 编码并作为请求负载发送:

// {"params":{"heroId":123,"power":"Death ray"}}
$http.put("/api/test", {
   params: { heroId: 123, power : "Death ray" }
})

使用 PUT 时如何强制将参数添加到查询字符串中?

【问题讨论】:

    标签: angularjs asp.net-web-api


    【解决方案1】:

    对于$http.put$http.post$http.patch,包含您的url 参数的config 对象作为第三个参数,第二个参数是请求正文:

    $http.put("/api/test",                                       // 1. url
              {},                                                // 2. request body
              { params: { heroId: 123, power : "Death ray" } }   // 3. config object
    );
    

    $http.putdocumentation供参考

    【讨论】:

    • 拯救了我的一天,谢谢
    【解决方案2】:

    AngularJS 发送 json 数据而不是 x-www-form-urlencoded 格式数据。 尽管您可以尝试以下方法:

    $http.put("/api/test", { heroId: 123, power : "Death ray" });
    

    【讨论】:

      【解决方案3】:

      如果你的 api url 是“api/test/heroId/power”,

      var data = 123+'/死亡射线'

      $http.put("api/test"+data);

      【讨论】:

      • 你肯定误解了这个问题。参数进入查询字符串,而不是路径。
      猜你喜欢
      • 2021-07-17
      • 2019-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多