How come I can't url encode this URL in 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(ur开发者_运维问答l);
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?
The '
is allowed in plain in the URI query. Here are the corresponding 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 = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
As you can see, sub-delims contains a plain '
. So the result is valid.
it is encoded correctly, if you type the same query into google sear field manually you will get this address:
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
and encodeURIComponent
is not a Node.js module, but part of standard javascript library
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");
精彩评论