简体   繁体   English

如何在 react-apollo 中为每个请求发送公共变量?

[英]How to send common variable with every request in react-apollo?

I am trying to send a common variable with every request through react-apollo.我正在尝试通过 react-apollo 为每个请求发送一个公共变量。 So I tried with ApolloLink to add variable in the operation, but while inspecting the.network I can't see the variable going with the query.所以我尝试使用ApolloLink在操作中添加变量,但是在检查 .network 时我看不到变量与查询一起使用。

Here's how I have written the middleware:这是我编写中间件的方式:


const authLink2 = new ApolloLink((operation, forward) => {
    operation.variables['entityId'] = '633'// localStorage.getItem('entityId');

    operation.setContext(({ headers }) => {
        const token = localStorage.getItem(AUTH_TOKEN);
  
        return {
            headers: {
                ...headers,
                Authorization: token ? `JWT ${token}` : "",
            }
        }
    });
    
    // until this log I can see the entityId variable has been appended
    console.log('operation', operation); 
    return forward(operation);
});

// creating ApolloClient
export const client = new ApolloClient({
    link: authLink2.concat(httpLink),
    cache
});

If this is not possible with ApolloLink middlware, please help me find a way to append the variable with every request.如果使用 ApolloLink 中间件无法做到这一点,请帮助我找到一种方法来为每个请求提供 append 变量。

you can sent anything in the header like this and access it in backend您可以像这样在 header 中发送任何内容并在backend访问它

const httpLink = createHttpLink({
  uri: `${configEnv.BASE_URL}/graphql`,
});

const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = localStorage.getItem(LOCAL_CONSTANT.TOKEN);
  const userToken = token ? JSON.parse(token) : null;
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      Authorization: userToken?.accessToken ? `Bearer ${userToken?.accessToken}` : '',
      testingVariable: '633'
    },
  };
});

export const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM