1

由于跨域问题,我有一个通过 JSONP 使用的 rest api,我实现了一个错误记录器,它捕获页面上发生的每个错误并将其发布到服务器,错误记录器的 uri 类似于:

user/{userId}/message/{errorMessage}/browser/{browser}/browserVer/{browserVer}/secure/{secure}/os/{os}/location/{location}"

位置变量有问题,如何在 uri 中传递 window.location.href ?

我试过 escape,encodeuri,encodeuricomponent 我必须base64吗?谢谢

4

1 回答 1

0

URI 的转义序列在RFC2396(统一资源标识符)的第 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 还在第 3.3 节path中为组件定义了保留字符:

Within a path segment, the characters "/", ";", "=", and "?" are reserved.

因此,您需要使用encodeURIComponent()因为escape()已被弃用并且encodeURI() 不会转义所有需要根据上面的 RFC 摘录转义的保留字符。

下面的示例显示只有encodeURIComponent()正确转义斜杠(这些字符最有可能导致您面临的问题):

>>> escape('//');
"//"

>>> encodeURI('//');
"//"

>>> encodeURIComponent('//');
"%2F%2F"

但是请注意,如果可能,您应该使用 POST 而不是 GET。这是在 REST(和一般情况下)中使用的正确方法,因为您将数据从客户端发送到服务器 (POST),而不是从服务器获取数据 (GET)。

使用 POST 还可以让您避免其他问题。由于普通 Web 服务器中 URI 的长度受到限制,迟早你会遇到一个带有很长 URI 的请求,该请求要么被修剪,要么引发错误。切换到 POST 将允许您保持 URI 干净,并将数据保留在消息正文而不是 URI 中。有关URI 长度限制的详细信息,请参阅此问题的答案。

于 2011-01-26T00:28:21.070 回答