Angularjs如何URI组件连接codeD [英] Angularjs How uri components are encoded
问题描述
我用的是标准的JavaScript函数连接codeURIComponent
期待AngularJS为en code查询字符串参数。根据以下测试它不是这种情况:
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连接codeS 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
要总结一下:
- 预计编码:
你好%20from%20http%3A%2F%2Fexample.com
- 实际的编码:
你好+在+的http:%2F%2Fexample.com
- Expected encoding:
Hello%20from%20http%3A%2F%2Fexample.com
- Actual encoding:
Hello+from+http:%2F%2Fexample.com
什么URI组件(又名查询字符串参数)的编码方法应该我期待着与AngularJS?
What uri component (aka query string parameters) encoding method should I expect with AngularJS?
推荐答案
角(至少1.3)不会只使用EN codeURIComponent并改变一些替代品(如,以+)。
Angular (at least 1.3) doesn't only use encodeURIComponent and changes some replacements (like " " to "+").
这是提交解释为什么:
的https://github.com/angular/angular.js/commit/9e30baad3feafc82fb2f2011fd3f21909f4ba29e
this is the commit explaining why : https://github.com/angular/angular.js/commit/9e30baad3feafc82fb2f2011fd3f21909f4ba29e
和这里就是你可以在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' : '+'));
}
注意, pctEn codeSpaces
很难coded到真正
;
下面是你可以做脱code 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组件连接codeD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!