【发布时间】:2021-01-15 03:42:05
【问题描述】:
目前,如果我从我的 react 应用程序运行 graphql 突变,它们将不起作用,因为标头中缺少授权令牌。我有一个要插入到标头中的管理机密,但我不知道该怎么做。
import { ApolloClient } from 'apollo-client';
import { InMemoryCache, NormalizedCacheObject } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
import { ApolloProvider } from '@apollo/react-hooks';
....
const cache = new InMemoryCache();
const link = new HttpLink({
uri: 'https://api/graphql',
});
const client: ApolloClient<NormalizedCacheObject> = new ApolloClient({
cache,
link,
});
ReactDOM.render(
<ThemeProvider theme={theme}>
<CssBaseline />
<ApolloProvider client={client}>
<BrowserRouter>
<App />
</BrowserRouter>
</ApolloProvider>
</ThemeProvider>,
document.querySelector('#root'),
);
我的 Apollo.config.js 文件中也有这个:
module.exports = {
client: {
service: {
url: 'https://api/graphql',
headers: {
'x-hasura-admin-secret': 'xxx',
},
},
excludes: ['src/graphql/index.tsx'],
},
};
如何在标头中包含令牌?应该是这样的:
'Authorization', `Bearer ${token}
在另一个 React Native 项目中也使用了相同的 API,他们获得了这样的令牌:
import auth from '@react-native-firebase/auth';
...
const token = await auth().currentUser?.getIdToken();
但我不知道如何在反应中实现这一点。
我也试过这样:
import { createHttpLink, InMemoryCache, ApolloClient } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
const httpLink = createHttpLink({
uri: 'https://graphql',
});
const authLink = setContext((_, { headers }) => {
const token = 'XX';
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
}
}
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
但我在这里得到一个错误:
<ApolloProvider client={client}>
那个:
Type 'ApolloClient<NormalizedCacheObject>' is missing the following properties from type 'ApolloClient<any>': store, writeData, initQueryManager
【问题讨论】:
-
我已经尝试过了,但它在客户端
<ApolloProvider client={client}>上给了我Type 'ApolloClient<NormalizedCacheObject>' is missing the following properties from type 'ApolloClient<any>': store, writeData, initQueryManager。无论哪种方式,都可以在这里使用admin secret作为令牌吗? @DanielA.White
标签: javascript reactjs graphql jwt apollo