为什么我不能在node.js中对此URL进行url编码?

时间:2011-09-04 12:19:42

标签: javascript url encoding node.js

$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);

结果如下:

"http://google.com/?q=q=what's%20up"

请注意单引号未正确编码的方式。 node.js模块有问题吗?

2 个答案:

答案 0 :(得分:12)

URI查询中允许'。以下是相应的production rules for the URI query as per RFC 3986

query         = *( pchar / "/" / "?" )
pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded   = "%" HEXDIG HEXDIG
sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
              / "*" / "+" / "," / ";" / "="

如您所见, sub-delims 包含普通'。所以结果是有效的。

答案 1 :(得分:4)

它编码正确,如果您手动在谷歌搜索字段中输入相同的查询,您将获得此地址:

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

请注意&q=what's+up&部分

encodeURIComponent不是Node.js模块,而是标准javascript库的一部分

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent

手动解决方法:

$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");