【问题标题】:Rest API : passing the window.location.href in the REST uriRest API:在 REST uri 中传递 window.location.href
【发布时间】:2011-01-25 18:33:22
【问题描述】:

由于跨域问题,我有一个通过 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 吗? 谢谢

【问题讨论】:

    标签: rest uri window.location


    【解决方案1】:

    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() 一直是deprecatedencodeURI() 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

    【讨论】:

    • 感谢您的详细回答,我会尝试找出有问题的字符,也许只是删除它们。因为我在 JSONP 中工作,所以我不能发帖强硬
    • 哦,我明白了(JSONP)。如果您以后不需要重新构建 URI,那么删除字符当然是一个不错的选择。不过,如果您的 API 允许,您可能需要考虑将参数从路径组件移动到查询字符串 - 这将帮助您避免 URI 长度限制。我们在一个项目中遇到过它,因为这根本不是一次好的体验:-/ 请注意,您仍然需要 encodeURIComponent() 来替代查询字符串,因为具有自己的查询参数的 {location} 值可能会破坏请求(由于与现在相同的原因)。
    • 感谢有关查询字符串的提示,我最终使用 base64 作为位置参数,因为我不想以特定字符开头。
    猜你喜欢
    • 2011-04-09
    • 2019-07-25
    • 2018-06-05
    • 1970-01-01
    • 2020-08-27
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多