4

我在我的 ReactJS RelayJS 网络环境中使用 JWT 身份验证。服务器和客户端中的所有令牌检索和处理都很好。我正在使用反应路由器 v4 进行路由。

我的问题是当我收到Unauthorized来自服务器的消息时(状态码 401)。如果用户在令牌过期后指向应用程序页面,就会发生这种情况,即。我需要做的是重定向到登录页面。这是我希望我能拥有的代码:

import { Environment, Network, RecordSource, Store } from 'relay-runtime';

const SERVER = 'http://localhost:3000/graphql';

const source = new RecordSource();
const store = new Store(source);

function fetchQuery(operation, variables, cacheConfig, uploadables) {
  const token = localStorage.getItem('jwtToken');

  return fetch(SERVER, {
    method: 'POST',
    headers: {
      Authorization: 'Bearer ' + token,
      Accept: 'application/json',
      'Content-type': 'application/json'
    },
    body: JSON.stringify({
      query: operation.text, // GraphQL text from input
      variables
    })
  })
    .then(response => {
      // If not authorized, then move to default route
      if (response.status === 401)
          this.props.history.push('/login') <<=== THIS IS NOT POSSIBLE AS THERE IS NO this.history.push CONTEXT AT THIS POINT
      else return response.json();
    })
    .catch(error => {
      throw new Error(
        '(environment): Error while fetching server data. Error: ' + error
      );
    });
}

const network = Network.create(fetchQuery);

const handlerProvider = null;

const environment = new Environment({
  handlerProvider, // Can omit.
  network,
  store
});

export default environment;

自然调用this.props.history.push是不可能的,因为网络环境不是 ReactJS 组件,因此没有关联的属性。

我试图在这一点上抛出一个错误,比如:

      if (response.status === 401)
          throw new Error('Unauthorized');

但是我在浏览器控制台上看到了错误,这在代码中无法正确处理。

我想做的就是在收到 401 错误的情况下重定向到登录页面,但我找不到正确的方法。

4

2 回答 2

0

您可以使用useEnvironment自定义钩子

export const useEnvironment = () => {
  const history = useHistory(); // <--- Any hook using context works here

  const fetchQuery = (operation, variables) => {
    return fetch(".../graphql", {...})
      .then(response => {
         //...
         // history.push('/login');
         //...
      })
      .catch(...);
  };

  return new Environment({
    network: Network.create(fetchQuery),
    store: new Store(new RecordSource())
  });
};

// ... later in the code

const environment = useEnvironment();

或者,如果您使用类组件,则可以创建 HOC 或渲染道具组件。

顺便说一句:这样你也可以避免使用localStorage会降低性能的。

于 2020-03-01T15:23:32.637 回答
0

我没有使用中继,而是使用渲染道具。我遇到了同样的问题。我能够使用 window 对象解决它。

 if (response.statusText === "Unauthorized") {
     window.location = `${window.location.protocol}//${window.location.host}/login`;
 } else {
   return response.json();
 }
于 2018-06-15T15:28:49.047 回答