javascript - Angularjs uri组件是如何编码的

标签 javascript angularjs uriencoding

我期望 AngularJS 使用标准 javascript 函数 encodeURIComponent 对查询字符串参数进行编码。根据下面的测试不是这样的:

describe('$http', function () {
 it('encodes uri components correctly', inject(function($http, $httpBackend) {
   var data = 'Hello from http://example.com';
   $httpBackend.expectGET('/api/process?data=' + encodeURIComponent(data));
   $http({ method: 'GET', url: '/api/process', params: { data: data } });
   $httpBackend.flush();
 }));
});

测试失败,出现以下错误:

$http encodes uri components correctly
Error: Unexpected request: GET /api/process?data=Hello+from+http:%2F%2Fexample.com
Expected GET /api/process?data=Hello%20from%20http%3A%2F%2Fexample.com

总结:

  • 预期编码:Hello%20from%20http%3A%2F%2Fexample.com
  • 实际编码:Hello+from+http:%2F%2Fexample.com

AngularJS 应该采用哪种 uri 组件(又名查询字符串参数)编码方法?

最佳答案

Angular(至少 1.3)不仅使用 encodeURIComponent 并且更改了一些替换(例如“”到“+”)。

这是解释原因的提交: https://github.com/angular/angular.js/commit/9e30baad3feafc82fb2f2011fd3f21909f4ba29e

这是您可以在 1.3 源代码中看到的内容:

/**
 * This method is intended for encoding *key* or *value* parts of query component. We need a custom
 * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
 * encoded per http://tools.ietf.org/html/rfc3986:
 *    query       = *( pchar / "/" / "?" )
 *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
 *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
 *    pct-encoded   = "%" HEXDIG HEXDIG
 *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
 *                     / "*" / "+" / "," / ";" / "="
 */
function encodeUriQuery(val, pctEncodeSpaces) {
  return encodeURIComponent(val).
             replace(/%40/gi, '@').
             replace(/%3A/gi, ':').
             replace(/%24/g, '$').
             replace(/%2C/gi, ',').
             replace(/%3B/gi, ';').
             replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}

请注意,pctEncodeSpaces 被硬编码为 true

下面是解码 URI 参数的方法

decodeURIComponent(val.
             replace('@', '%40').
             replace(':', '%3A').
             replace('$', '%24').
             replace(',', '%2C').
             replace(';', '%3B').
             replace('+', '%20'));

关于javascript - Angularjs uri组件是如何编码的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24542465/

相关文章:

javascript - multi ng -重复并删除 Angular js中的行

javascript - 如何使用underscore.js对文本混合数字进行排序

javascript - 将 Angular 服务与 NodeJS 模块相结合

javascript - Google map 调整大小并居中,意外行为

javascript - 如何在 AngularJS 中显示隐藏元素?

javascript - Primefaces commandButton onClick Javascript 调用

javascript - Vue.js - 将新数据添加或设置到存储中的数组

php - CodeIgniter 抛出 "The URI you submitted has disallowed characters...",我看不出是什么原因造成的

tomcat - Tomcat设置URIEncoding有什么意义?

javascript - URIencode 和冒号