URI 的转义序列在 RFC2396(统一资源标识符)的 section 2.4.1 中定义:
An escaped octet is encoded as a character triplet, consisting of the
percent character "%" followed by the two hexadecimal digits
representing the octet code. For example, "%20" is the escaped
encoding for the US-ASCII space character.
escaped = "%" hex hex
hex = digit | "A" | "B" | "C" | "D" | "E" | "F" |
"a" | "b" | "c" | "d" | "e" | "f"
该 RFC 还为 section 3.3 中的 path 组件定义了保留字符:
Within a path segment, the characters "/", ";", "=", and "?" are reserved.
所以您需要使用encodeURIComponent(),因为escape() 一直是deprecated 和encodeURI() does not escape all reserved characters,需要根据上面的RFC 摘录进行转义。
下面的示例显示只有encodeURIComponent() 可以正确转义斜杠(这些字符最有可能导致您面临的问题):
>>> escape('//');
"//"
>>> encodeURI('//');
"//"
>>> encodeURIComponent('//');
"%2F%2F"
但是请注意,如果可能,您应该使用 POST 而不是 GET。这是在 REST(以及一般情况下)中使用的正确方法,因为您将数据从客户端发送到服务器 (POST),而不是从服务器 (GET) 获取数据。
使用 POST 还可以避免其他问题。由于普通 Web 服务器中 URI 的长度受到限制,迟早你会遇到一个带有很长 URI 的请求,该请求要么被修剪,要么引发错误。切换到 POST 将允许您保持 URI 干净,并将数据保留在消息正文中,而不是 URI。有关 URI 长度限制的详细信息,请参阅 answers to this question。