请教 url encode 问题

112 天前
 chaleaochexist
https://192.168.1.1:25505/api/v1/query?query=sum(a:b:c:d:e{a="", b="c"}) by (namespace)

用 postman 转成 curl 是这样子的

curl --location --globoff 'https://192.168.1.1:25505/api/v1/query?query=sum(a%3Ab%3Ac%3Ad%3Ae{a%3D%22%22%2C%20b%3D%22c%22})%20by%20(namespace)'

可以看到对参数部分编码了:

  1. 冒号 :
  2. 等于号 =
  3. 引号 "
  4. 逗号 ,

就是没有 encode 括号()和大括号{}

我的问题是: 为啥没有 encode 大小括号?

1231 次点击
所在节点    程序员
11 条回复
lzgshsj
112 天前
有什么问题,你自己在控制台 encodeURI 一下就知道了。括号本来就不需要 encode 。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI
MegatronKing
112 天前
这是个好问题,我也遇到过。比如 * 号,RFC 规范里面没有明确定义是否需要 encode 导致不同版本的实现不相同,有的库会 encode 有的不会,很容易因为前后端不一致出现问题。
Subfire
112 天前
为什么要 encode? 现代浏览器早已支持了 URL 中有 Unicode
5200
112 天前
要不你直接 base64 一下,https://192.168.1.1:25505/api/v1/query?query=base64 码,
get 方式记得挺多问题的,复杂编码最好用 post 或者 head 头试试。
chaleaochexist
112 天前
@lzgshsj 你这是个函数和标准有啥关系? mozilla 也不是标准.

@MegatronKing 那就是说, 最后还是要看客户端和服务端之间的协议了...

@Subfire 因为我不用浏览器.

@5200 额...base64 也支持吗? 那还真不错. 我学习一下.
morenacl
112 天前
sum%28a%3Ab%3Ac%3Ad%3Ae%7Ba%3D%22%22%2C%20b%3D%22c%22%7D%29%20by%20%28namespace%29%0A, 这是标准 url 编码后的结果
lzgshsj
112 天前
@chaleaochexist 额。。。首先 postman 是 electron 的,electron 是 nodejs ,你说我为啥要给你看 js 的文档。其次,你压根就没看我给的链接吗。里面都说了为什么 encode 会保留括号。

encodeURI() escapes all characters except:

A–Z a–z 0–9 - _ . ! ~ * ' ( )

; / ? : @ & = + $ , #
The characters on the second line are characters that may be part of the URI syntax, and are only escaped by encodeURIComponent(). Both encodeURI() and encodeURIComponent() do not encode the characters -.!~*'(), known as "unreserved marks", which do not have a reserved purpose but are allowed in a URI "as is". (See RFC2396)
virusdefender
112 天前
这个大家的实现其实差异挺大的,如果不放心可以把所有的字符都编码,也是可以的。
jiangzm
112 天前
#4 base64 也不能直接用做 url param ,需要转义几个字符,这种特殊的 base64 有另外的名字叫 safeBase64
lzgshsj
112 天前
另外,根据 https://tc39.es/ecma262/multipage/global-object.html#sec-uri-handling-functions
其中
> NOTE 1
The set of reserved characters is based upon RFC 2396 and does not reflect changes introduced by the more recent RFC 3986.
可以得知是根据 RFC 2396 的保留字符来的。
然后,根据 RFC 2396 https://www.ietf.org/rfc/rfc2396.txt

> 2.2. Reserved Characters
reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
"$" | ","
> 2.3. Unreserved Characters
unreserved = alphanum | mark

mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"

这下应该清楚了吧
KouShuiYu
112 天前
! # $ & ' ( ) * + , / : ; = ? @ [ ]
保留字符不需要编码
https://en.wikipedia.org/wiki/Percent-encoding

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1009606

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX