我在登录后获得访问令牌,我想将该令牌分配给App.js标头中的授权我正在使用异步存储将访问令牌存储在本地存储中,并且想分配给App.js文件中的标头。我该怎么做。我想为标头中的授权分配令牌,以便可以进行graphql API调用
MY App.js文件
import React, {Component} from 'react';
import {AppRegistry,SafeAreaView, StyleSheet} from 'react-native';
import Navigator from "@Navigation"
import AsyncStorage from '@react-native-community/async-storage';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-boost';
const httpLink = createHttpLink({
uri: 'https://graphql.sample.com/graphql',
});
const token = AsyncStorage.getItem('@accessToken')
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
authorization: token ,
}
}
});
const link = authLink.concat(httpLink)
const cache = new InMemoryCache();
const defaultOptions = {
query: {
fetchPolicy: "network-only",
errorPolicy: "all"
}
};
const client = new ApolloClient({
link,
cache,
defaultOptions
});
class App extends Component {
render() {
return (
<ApolloProvider client={client}>
<Navigator/>
</ApolloProvider>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
});
export default App;
您应该先等待AsyncStorage.getItem('@accessToken')
才能获取accessToken,然后再将其传递给authorization: token
。这是与React Native中的Waiting for AsyncStorage.getItem()
相关的帖子。试试这个: