【问题标题】:How to parse the complete link in the url query string?如何解析 url 查询字符串中的完整链接?
【发布时间】:2021-07-13 07:55:15
【问题描述】:

网址:https://n9hon.csb.app?name=netflix&url=https://localhost?apikey=123&code=321

代码:

import { useLocation } from "react-router-dom";

function useQuery() {
  const {search} = useLocation();
  const query = new URLSearchParams(search);
  console.log('name: ', query.get('name'))
  console.log('url: ', query.get('url'))
  return query
}

输出:

name:  netflix 
url:  https://localhost?apikey=123 

如您所见,code 参数丢失了。我希望url 参数的值应该是https://localhost?apikey=123&code=321

包版本:

"react-router-dom": "5.2.0"

【问题讨论】:

  • url 值应该被转义,这样& 将是&https://n9hon.csb.app?name=netflix&url=https://localhost?apikey=123&code=321.

标签: javascript react-router react-hooks react-router-dom urlsearchparams


【解决方案1】:

发生这种情况是因为您没有对 URI 组件进行编码。您可以使用encodeURIComponentdecodeURIComponent 函数来解决您的问题。在推送到路由之前对 URL 进行编码,在接收到之后就可以对其进行解码。

注意:请注意不需要解码,因为new URLSearchParams(search).get('key') 命令会自动解码组件。

// In navigating component

const history = useHistory();

return (
    ...
    <button onClick={() => history.push(`/?name=netflix&url=${encodeURIComponent('https://localhost?apikey=123&code=321')}`)}>
        Go to link
    </button>
    ...
)
import { useLocation } from "react-router-dom";

function useQuery() {
  const {search} = useLocation();
  const query = new URLSearchParams(search);
  console.log('name: ', query.get('name'))    // name: netflix 
  console.log('url: ', query.get('url'))      // url: https://localhost?apikey=123&code=321 
  return query;
}

【讨论】:

    【解决方案2】:

    您的代码是正确的,但您输入的 URL 是错误的。

    如果你使用:

    https://n9hon.csb.app?name=netflix&url=https://localhost?apikey=123&code=321
    

    您的浏览器会将其读取为

    Protocoll
    https:
                    Top Level Domain
                     .app
                 Domain
                  csb
          Sub-Domain
            n9hon
                             Params
                         ?name=netflix&url=https://localhost?apikey=123&code=321
    

    到目前为止还可以,但随后事情就付诸东流了:

                            Param 1
                          name=netflix
                                              Param 2
                                       url=https://localhost?apikey=123
                                                                         Param 3
                                                                        code=321
    

    如果您想将 Param2 和 Param 3 作为一个 Param 读取,您需要去掉 &(并且还要清除 ? : = 和 /)

    https://n9hon.csb.app?name=netflix&url=https%3A%2F%2Flocalhost%3Fapikey%3D123%26amp%3Bcode%3D321

    在您的代码中,您可以通过encodeURI(uri) 轻松执行此操作,并通过decodeURI(enc) 恢复它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      • 1970-01-01
      • 2022-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多