React 中的@apollo/client,传递标头不起作用

问题描述 投票:0回答:1

我试图在 @apollo/client useQueryQuery 中传递标头,但它没有被传递。 点击登录按钮将调用loginRequest。它是使用 Graphql 的 REST 调用。 重要 -> 在 loginRequest 中,很多地方都会被调用,有些地方需要传递标头,有些地方则不需要。 下面我添加了查询和代码示例。

查询

export const USER_LOGIN = gql`
  fragment LoginInput on REST {
    username: String
    password: String
  }
  query UserLogin($input: LoginInput!) {
    userLogin(input: "input", body: $input)
      @rest(
        type: "Any"
        path: "iam/api/sso/authentication/login"
        method: "POST"
        bodyKey: "body"
      ) {
      access_token
      accessTokenExpired
      lastDateTimeAccessToken
      lastDateTimeRefreshToken
      expires_in
      refresh_expires_in
      refresh_token
      token_type
      id_token
    }
  }
`;
function Login(){

const [loginRequest, data] = useLazyQuery<{userLogin: LoginResponse;}>(USER_LOGIN, {
fetchPolicy: "network-only",
})
const handleLogin=()=>{
  loginRequest(
    variables: {
        input: {
          username: `[email protected]`,
          password: 123,
        },
    context: {
        headers: {
            "x-custom-header": "abc"
        }
       }
      }
)
}
return <>
  <button onClick={handleLogin}> Login</button>
</>
}
reactjs graphql apollo apollo-client react-apollo
1个回答
0
投票

请使用 Apollo links 设置(或获取)标题。

这是一个身份验证链接示例:

import { ApolloLink } from '@apollo/client';

const authLink = new ApolloLink((operation, forward) => {
  operation.setContext(({ headers }) => ({ headers: {
    authorization: Auth.userId(), // however you get your token
    ...headers
  }}));
  return forward(operation);
});
© www.soinside.com 2019 - 2024. All rights reserved.