javascript 为什么我不能在 node.js 中对这个 URL 进行 url 编码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7299149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How come I can't url encode this URL in node.js?
提问by TIMEX
$node
querystring = require('querystring')
var dict = { 'q': 'what\'s up' };
var url = 'http://google.com/?q=' + querystring.stringify(dict);
url = encodeURIComponent(url);
console.log(url);
The result is this:
结果是这样的:
"http://google.com/?q=q=what's%20up"
Notice how the single quote is not encoded correctly. Is there something wrong with the node.js module?
注意单引号是如何编码不正确的。node.js 模块有问题吗?
回答by Gumbo
The '
is allowed in plain in the URI query. Here are the corresponding production rules for the URI query as per RFC 3986:
的'
是允许在普通的URI的查询。以下是根据 RFC 3986 的 URI 查询的相应生产规则:
query = *( pchar / "/" / "?" ) pchar = unreserved / pct-encoded / sub-delims / ":" / "@" unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" pct-encoded = "%" HEXDIG HEXDIG sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
query = *( pchar / "/" / "?" ) pchar = unreserved / pct-encoded / sub-delims / ":" / "@" unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" pct-encoded = "%" HEXDIG HEXDIG sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
As you can see, sub-delimscontains a plain '
. So the result is valid.
如您所见,sub-delims包含一个普通的'
. 所以结果是有效的。
回答by Marek Sebera
it is encoded correctly, if you type the same query into google sear field manually you will get this address:
它被正确编码,如果您手动在 google sear 字段中键入相同的查询,您将获得以下地址:
http://www.google.cz/#hl=cs&cp=8&gs_id=u&xhr=t&q=what's+up&pf=p&sclient=psy&site=&source=hp&pbx=1&oq=what's+u&aq=0&aqi=g5&aql=&gs_sm=&gs_upl=&bav=on.2,or.r_gc.r_pw.&fp=792ecf51920895b2&biw=1276&bih=683
note that &q=what's+up&
part
注意那&q=what's+up&
部分
and encodeURIComponent
is not a Node.js module, but part of standard javascript library
并且encodeURIComponent
不是 Node.js 模块,而是标准 javascript 库的一部分
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent
manual workaround:
手动解决方法:
$node
querystring = require('querystring')
var dict = { 'q': 'what\'s up' };
var url = 'http://google.com/?q=' + querystring.stringify(dict);
url = encodeURIComponent(url);
url = url.replace(/'/g,"%27");