0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

node.jsでシングルクォートのURLエンコード

Posted at

encodeURIComponentで'シングルクォートをエンコードすると'のままだけど、node.jsのurlモジュールでurl.parseの結果のpathを見ると%27になっている。

経緯

とある開発中のREST APIで、'シングルクォートが含まれるURLをrequestモジュールからうまく取得できない問題にあたった。(そのAPIがシングルクォートはシングルクォートのままエンコードされずに送られることを想定していた。ブラウザからアクセスしたら問題なく動作してた)

requestモジュールで引数に渡したURLが、内部でnode.jsのurlモジュールでurl.parseされる。そのときに、シングルクォートが%27にエンコードされてたみたいだった。

結論

REST API側が、decodeURIComponentしてから、シングルクォートを扱ってれば問題なかったので、ちゃんとdecodeURIComponentするよう気を付ける。

検証

他の記号も同様の挙動か検証したが'シングルクォートだけだった
なぜこうなってるのかは知らない

const url = require("url");

const letters = '!"$&\'()=-~^|\\`@{}[]+;*:<>,.?/_';
letters.split("").forEach((c) => {
  const parsed = url.parse(c).path;
  const encoded = encodeURI(c);
  console.log(c, parsed, encoded);
});
! ! !
" %22 %22
$ $ $
& & &
' %27 '
( ( (
) ) )
= = =
- - -
~ ~ ~
^ %5E %5E
| %7C %7C
\ / %5C
` %60 %60
@ @ @
{ %7B %7B
} %7D %7D
[ [ %5B
] ] %5D
+ + +
; ; ;
* * *
: : :
< %3C %3C
> %3E %3E
, , ,
. . .
? ? ?
/ / /
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?