【问题标题】:Issues with identifying and encoding urls识别和编码网址的问题
【发布时间】:2020-11-12 03:31:09
【问题描述】:

我在解析/操作 URI 时遇到问题:

问题陈述:

我想编码 f[users.comma] 并返回它。

[Case-1] 我从后端服务获取一个 url,编码 f[users.comma] 并返回它。

[Case-2] 我从后端服务获得一个 url,并且 f[users.comma] 已经编码。所以不要双重编码并返回它。

预期输出:

`/demo/bigquery/order_items?fields=users.email&f[users.comma]=%22Abbeville%2C+Georgia%22`

代码:

const encodedExample = `/demo/bigquery/order_items?fields=users.email&f[users.comma]=%22Abbeville%2C+Georgia%22` // the last param is encoded

const regularExample2 = `/demo/bigquery/order_items?fields=users.email&f[users.comma]="Abbeville, Georgia"` // 

const specialEncode = (url) => {
          for (let queryParam of urlObj) {
            const [urlKey, urlValue] = queryParam

            // Check to see if url contains f[users.comma]
            if (urlKey.includes('f[')) {
              urlObj.set(urlKey, encodeURI(urlValue))
            }
          }

          return urlObj.toString() // doesn't seem to work 
}

我觉得我的方法正在越野。我会很感激这里的一些帮助。

【问题讨论】:

    标签: javascript url


    【解决方案1】:

    由于后端服务返回一个编码或解码的 url

    我们可以先从后端服务解码url(如果url已经编码,这不会产生任何异常)

    const encodedExample = `/demo/bigquery/order_items?fields=users.email&f[users.comma]=%22Abbeville%2C+Georgia%22` // the last param is encoded
    
    const regularExample2 = `/demo/bigquery/order_items?fields=users.email&f[users.comma]="Abbeville, Georgia"` 
    
    const specialEncode = (url) => {
      let decodedUrl = decodeURI(url);
      let encodedUrl = encodeURI(decodedUrl);
      
      // fix "f[users.comma]" because encodeURI will encode the [ and ] as well
      encodedUrl = encodedUrl.replace("f%5Busers.comma%5D", "f[users.comma]")
      
      console.log(encodedUrl);
      return encodedUrl;
    }
    
    specialEncode(encodedExample); // logs and returns: /demo/bigquery/order_items?fields=users.email&f[users.comma]=%22Abbeville%252C+Georgia%22
    
    specialEncode(regularExample2); // logs and returns: /demo/bigquery/order_items?fields=users.email&f[users.comma]=%22Abbeville%252C+Georgia%22

    上面的代码对编码和解码的 url 都适用

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 2019-09-14
      • 1970-01-01
      相关资源
      最近更新 更多