Angularjs uri 组件是如何编码的 [英] Angularjs How uri components are encoded
问题描述
我期望 AngularJS 使用标准的 javascript 函数 encodeURIComponent
对查询字符串参数进行编码.根据以下测试,情况并非如此:
I was expecting AngularJS to encode query string parameters using the standard javascript function encodeURIComponent
. According to the following test it is not the case:
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();
}));
});
测试失败,出现以下错误:
The test fails with the following error:
$http 正确编码 uri 组件
错误:意外请求:GET/api/process?data=Hello+from+http:%2F%2Fexample.com
预期 GET/api/process?data=Hello%20from%20http%3A%2F%2Fexample.com
$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 组件(又名查询字符串参数)编码方法?
What uri component (aka query string parameters) encoding method should I expect with AngularJS?
推荐答案
Angular(至少 1.3)不仅使用 encodeURIComponent 并且更改了一些替换(例如"到+").
Angular (at least 1.3) doesn't only use encodeURIComponent and changes some replacements (like " " to "+").
这是解释原因的提交:https://github.com/angular/angular.js/commit/9e30baad3feafc204fc82fb2f2011fd3f21909f4ba29e
您可以在 1.3 源中看到以下内容:
And here's what you can see in 1.3 sources :
/**
* 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
;
note that pctEncodeSpaces
is hardcoded to true
;
您可以执行以下操作来解码 URI 参数
Here's what you can do to decode URI parameters
decodeURIComponent(val.
replace('@', '%40').
replace(':', '%3A').
replace('$', '%24').
replace(',', '%2C').
replace(';', '%3B').
replace('+', '%20'));
这篇关于Angularjs uri 组件是如何编码的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!