【问题标题】:Why auth0's parseHash return undefined?为什么 auth0 的 parseHash 返回 undefined?
【发布时间】:2019-12-13 18:48:38
【问题描述】:

当我尝试使用 auth0 的 parseHash 时,我是 auth0 的新手。令我惊讶的是,这个函数以某种方式返回 null。我试图窥视source code,看来这个函数最终会尝试返回一些东西。

这是让我感到困惑的代码部分:

import React from 'react';
import { Link } from '@reach/router';
import './Callback.sass';

export const Callback = ({ auth, navigate }) => {
  let result = auth.parseHash((err, authResult) => {
    if (err) {
      return (
        <div className="error">
          <h1>{err.error}</h1>
          <p>{err.errorDescription}</p>
          <Link to="/">Home</Link>
        </div>
      );
    } else {
      console.log({ authResult });
      return 'profile';
      // localStorage.setItem('authResult', JSON.stringify(authResult));
      // navigate('/profile');
    }
  });
  console.log({ result });
  if (result) return result;
  return <React.Fragment />;
};

结果如下:

我认为这真的令人困惑。控制台记录“authResult”部分,但resultundefined。 (我什至用 async await 进行了测试,仍然无法达到我的预期)。

我目前只是包装结果来解决这个问题。

这是一个错误吗?还是我使用的方法不对?

【问题讨论】:

    标签: reactjs auth0 reach-router


    【解决方案1】:

    我也是 auth0 的新手,今天遇到了同样的错误。

    通过将parseHash 包装在 Promise 中解决了这个问题:

    /* ... */
    
    function handleAuthentication() {
      // wrap parseHash in a Promise
      return new Promise((resolve, reject) => {
        auth0.parseHash((err, authResult) => {
          if (authResult && authResult.accessToken && authResult.idToken) {
            resolve(authResult)
          } else if (err) {
            throw new Error(`Error: ${err.error}. Check the console for further details.`);
          } else {
            throw new Error(`Unknown error`);
          }
        })
      })
    }
    
    // wait for the Promise to resolve and log the result
    handleAuthentication()
      .then(function(result) {
        console.log(result);
      });
    

    您的代码中的问题是,您希望parseHash 直接返回结果,但事实并非如此(在第 22 行)。相反,它会调用您已正确注册的回调函数,因此您会在回调函数内部而不是外部得到预期结果。

    【讨论】:

      【解决方案2】:

      你的console.log({ result });

      在之前运行

      let result = auth.parseHash((err, authResult) =&gt; {

      所以将它包装在 Promise 中会有所帮助。

      【讨论】:

        【解决方案3】:

        代码没有任何问题...实际上,对于当前示例,您应该始终从安慰 auth.parseHash$() 中得到“无”,实际上,这是一个返回 Observable&lt;any&gt; 的回调。

        其目的是解析 url 哈希并提取 Auth 响应,返回您传入的一些自定义参数(准确地说是哈希段)。

        因此,如果您不希望返回一些您在请求授权时传入的哈希参数,auth.parseHash$() 将不会返回任何内容 - 链接 here

        【讨论】:

          猜你喜欢
          • 2018-07-21
          • 2019-10-26
          • 2018-12-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多