【问题标题】:How to encode URL in angularJS如何在 angularJS 中编码 URL
【发布时间】:2017-12-08 14:21:43
【问题描述】:

我正在尝试使用 anuglarjs http GET 请求从我的 Rest API 控制器获取数据。但是,我需要发送的参数包括“。”导致 URL 失败的符号。我试图对其进行编码,但它不起作用。这是我所做的:

function getApplication($http) {
    this.getData = function(application,name) {
      return $http({
        method : 'GET',
        url : http://localhost:8080/app/rest/+ 'app/' + encodeURIComponent(name)
      }).then(function successCallback(response) {
        return response.data;
      }, function errorCallback(response) {
        console.log(response.statusText);
      });
    }
  }

名称参数是app.01.com

我得到的网址结果是:

GET http://localhost:8080/app/rest/app/app.01.com 406 (Not Acceptable)

有人知道如何对 url 进行编码,以便我可以从 Rest Controller 获取数据吗? 谢谢

【问题讨论】:

  • 将名称作为对象传入请求正文。 {方法:'GET',网址:localhost:8080/app/rest/+'app/',数据:名称}
  • 在服务端听起来像是一个糟糕的实现。您可以尝试手动将. 替换为%2E。如果这样可行,则该服务的解析规则过于严格。

标签: angularjs rest angularjs-http


【解决方案1】:

使用 btoa 和 atob

<!DOCTYPE html>
<html>
<body>

<p>Click the button to decode a base-64 encoded string.</p>

<button onclick="myFunction()">Try it</button>

<p><strong>Note:</strong> The atob() method is not supported in IE9 and earlier.</p>

<p id="demo"></p>

<script>
function myFunction() {
    var str = "Hello World!";
    var enc = window.btoa(str);
    var dec = window.atob(enc);

    var res = "Encoded String: " + enc + "<br>" + "Decoded String: " + dec;
    document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>
function getApplication($http) {
    this.getData = function(application,name) {
      return $http({
        method : 'GET',
        url : http://localhost:8080/app/rest/+ 'app/' +  window.btoa(name)
      }).then(function successCallback(response) {
        return response.data;
      }, function errorCallback(response) {
        console.log(response.statusText);
      });
    }
  }

【讨论】:

    【解决方案2】:

    您是否尝试将 url 数据放入双引号中? url : "http://localhost:8080/app/rest/+ 'app/' + encodeURIComponent(name)"

    【讨论】:

      【解决方案3】:

      不可能是“。”是一个未保留字符,并且“在用相应的百分比编码的 US-ASCII 八位字节替换未保留字符方面不同的 URI 是等效的”。因此,/%2E 与 / 相同。 ,这将被规范化。

      那么您可以使用localhost:8080/app/rest/app/app%2E01.com 作为您的网址

      【讨论】:

        猜你喜欢
        • 2014-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-25
        • 2015-05-26
        • 1970-01-01
        • 2013-01-08
        相关资源
        最近更新 更多