设置阿波罗客户端标头时出现NetworkError

时间:2019-08-16 04:58:58

标签: react-native authentication jwt react-apollo

我正在使用react-native在apollo客户端中设置令牌身份验证,但是我的应用程序显示NetworkError。如果我删除所有身份验证设置,效果很好。

Error screenshot

这是用于本地演示应用程序,具有反应导航,阿波罗客户端,formik和yup。

App.js

const httpLink = new createHttpLink({
  uri: 'http://192.168.0.2/api/graphql'
});
const authLink = setContext((_, { headers }) => {
  const authToken = localStorage.getItem('authToken');
  return {
    headers: {
      ...headers,
      authorization: authToken ? `JWT ${authToken}` : '',
    }
  }
});

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

class App extends Component {
  render(){
    return (
      <ApolloProvider client={APIClient}>
        <SafeAreaView style={styles.container}>
          <AppContainer />
        </SafeAreaView>
      </ApolloProvider>
    );
  }
};

SignInScreen.js

const TOKENAUTH_MUTATION = gql`
  mutation SignIn($username: String!, $password: String!){
    tokenAuth(username: $username, password: $password){
      token
    }
  }
`;

class SignInForm extends Component{
  constructor(props){
    super(props);
  }

  render(){
    return(
      <View style={styles.container}>
        <Text style={styles.label}>Username:</Text>
        <TextInput
          autoCapitalize='none'
          autoFocus={true}
          onBlur={this.props.handleBlur('username')}
          onChangeText={this.props.handleChange('username')}
          style={styles.textInput}
          value={this.props.values.username}
        />
        <Text style={styles.helpTextInput}>{this.props.errors.username}</Text>
        <Text style={styles.label}>Password:</Text>
        <TextInput
          onBlur={this.props.handleBlur('password')}
          onChangeText={this.props.handleChange('password')}
          secureTextEntry={true}
          style={styles.textInput}
          value={this.props.values.password}
        />
        <Text style={styles.helpTextInput}>{this.props.errors.password}</Text>
        {this.props.isSubmitting ? (
          <ActivityIndicator />
        ) : (
          <Button title="Sign In" onPress={this.props.handleSubmit} />
        )}
      </View>
    );
  }
}

class SignInScreen extends Component{

  static navigationOptions = {
    title: "Sign In"
  };

  _submit(values, actions, mutateFunc){
    mutateFunc({
      variables: values
    });
  }

  async _onSuccess(dataResult){
    await AsyncStorage.setItem('authToken', dataResult.tokenAuth.token);
    this.props.navigation.navigate('Questions');
  }

  _onError(error){
    alert("ERROR: " + JSON.stringify(error));
  }

  render(){
    const formValidationSchema = yup.object().shape({
      username: yup.string().required().label("Username"),
      password: yup.string().required().label("Password")
    });

    return(
      <Mutation
        mutation={TOKENAUTH_MUTATION}
        onCompleted={dataResult => this._onSuccess(dataResult)}
        onError={error => this._onError(error)}>
        {(signInMutationFunc, {loading, error, data}) => {
          return (
            <Formik 
              initialValues={{
                username: '',
                password: ''
              }}
              onSubmit={(values, actions) => this._submit(values, actions, signInMutationFunc)}
              validationSchema={formValidationSchema}>
              {formProps => {
                return(<SignInForm {...formProps} />);
              }}
            </Formik>
          );
        }}
      </Mutation>
    );
  }
}

我希望令牌存储在每个请求中,并在标头中使用(如Apollo文档所说)。 如果我使用基本的ApolloClient,则可以使用,但不使用标题

const APIClient = new ApolloClient({
  uri: 'http://192.168.0.2/api/graphql'
});

我在Android和IOS设备中遇到相同的错误:'(

1 个答案:

答案 0 :(得分:0)

好 在我的示例中,我正在使用Apollo Boost。当我使用Apollo Client时,它可以工作。