代码之家  ›  专栏  ›  技术社区  ›  Martyn

访问React中的哈希参数(/callback#token=1234&…etc)

  •  2
  • Martyn  · 技术社区  · 6 年前

    我正在尝试使用密码授权从API获取Oauth令牌。当我重定向回/callback时,React正在将?.query转换/重定向为#…query:

    例如:

    http://localhost:3000/callback#access_token=eyJ0eXAiOi...&token_type=Bearer&expires_in=31535999

    props.location.hash ... 我应该把绳子切碎,还是有办法?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Alejandro    6 年前

    尝试 query-string

    import queryString from 'query-string';
    
    queryString.parse(props.location.hash)
    
    // { access_token: '...', token_type: '...' }
    

    也有类似的软件包: querystring , qs .

        2
  •  1
  •   dance2die    6 年前

    我建议使用smth这样的函数从 props.location.hash

    const getJsonFromUrl = str => {
      const query = str.substr(1);
      const result = {};
    
      query.split('&').forEach(function(part) {
        const item = part.split('=');
        result[item[0]] = decodeURIComponent(item[1]);
      });
    
      return result;
    };
    
    const { access_token, token_type } = getJsonFromUrl(props.location.hash);
    
        3
  •  0
  •   Bruno Pop    4 年前

    最佳方式:

    let params = new URLSearchParams(window.location.hash);
    let token = params.get('access_token');