【问题标题】:GraphQL mutation not being sent to request when using Apollo client?使用 Apollo 客户端时未将 GraphQL 突变发送到请求?
【发布时间】:2020-02-01 21:00:40
【问题描述】:

我遇到了一个问题,当使用来自 'apollo-boost'{ ApolloClient } 向我的后端服务器发送自定义标头时,我无法指定 URI
所以我不得不改用 'apollo-client' 中的{ ApolloClient }


该问题已解决,但现在我的突变没有被发送到后端?

我的突变:

import { gql } from 'apollo-boost';

export const LOGIN_USER = gql`
  mutation($email: String!, $password: String!) {
    loginUser(email: $email, password: $password) {
      userId
      token
      expiresIn
    }
  }
`
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';

const httpLink = new HttpLink({
  uri: 'http://localhost:3001/graphql'
})

const authLink = setContext((_, { headers }) => {
  const store = JSON.parse(sessionStorage.getItem('interdevs-data'));
  const token = store.token;

  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});
  const login = async (email, password) => {
    try {
        const user = await loginUser({
          variables: {
            email,
            password
          }
        });
        const { userId, token, expiresIn } = user.data.loginUser;

        setUserData({
          token: token,
          userId: userId,
          expiresIn: expiresIn
        });

        sessionStorage.setItem('interdevs-data', JSON.stringify({ 
          "token": token, 
          "userId": userId, 
          "expiresIn": expiresIn 
        }));
    } catch(err) {
      console.log('login error: ', err);
      setLoginErr(err);
    };
  };

这是我遇到的错误。

"Error: Network error: Cannot read property 'token' of null"

当我从 apollo-boost 切换回来导入 ApolloClient 时,它又可以工作了。


非常感谢任何帮助!

【问题讨论】:

    标签: javascript reactjs graphql


    【解决方案1】:

    不是 100% 确定,但我认为错误就在这里:

    const store = JSON.parse(sessionStorage.getItem('interdevs-data'));
    const token = store.token;
    

    如果没有键为interdevs-data 的项目,store 将为空

    我认为您可以通过这样做来解决它:

    const store = JSON.parse(sessionStorage.getItem('interdevs-data'));
    const token = store ? store.token : null;
    

    【讨论】:

    • 哦,谢谢,太好了,我会把它添加到我的代码中。但它返回 null 因为突变没有返回令牌,这是我的主要问题
    【解决方案2】:

    了解如何使用 apollo-boost 设置身份验证标头

    const client = new ApolloClient({
      uri: 'http://localhost:3001/graphql',
      request: operation => {
        const ssData = JSON.parse(sessionStorage.getItem('data'));
        operation.setContext({
          headers: {
            authorization: ssData ? `Bearer ${ssData.token}` : ''
          }
        });
       }
    });
    
    

    【讨论】:

      猜你喜欢
      • 2018-07-18
      • 2018-03-25
      • 2018-11-29
      • 2020-02-03
      • 2020-01-07
      • 2019-02-14
      • 1970-01-01
      • 2017-10-17
      • 2021-10-16
      相关资源
      最近更新 更多