我正在构建一个React + GraphQL应用程序并遇到一个奇怪的问题。下面的代码设置了ApolloClient,添加了一个承载令牌,然后尝试按id获取。
async componentDidMount() {
const id = this.props.match.params.id;
if (id !== 'new') {
const authLink = setContext(async (_, {headers}) => {
const token = await this.props.auth.getAccessToken();
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : ''
}
}
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
client.query({
query: gql`{
query GetPoints(id: Int) {
pointsGet(id: $id) {
date,
alcohol,
exercise,
diet,
notes
}
}
}
`,
variables: {id: id}
})
.then(result => {
console.log(result);
this.setState({points: result.data.points});
});
} else {
console.log('new!');
}
}
此代码导致以下错误:
Uncaught (in promise) Error: Network error: forward(...).subscribe is not a function
at new ApolloError (ApolloError.js:43)
at QueryManager.js:327
at QueryManager.js:762
at Array.forEach (<anonymous>)
at QueryManager.js:761
at Map.forEach (<anonymous>)
at QueryManager../node_modules/apollo-client/core/QueryManager.js.QueryManager.broadcastQueries (QueryManager.js:754)
at QueryManager.js:254
这里的代码(没有参数)工作正常:
async componentDidMount() {
const user = await this.props.auth.getUser();
this.setState({user});
const authLink = setContext(async (_, { headers }) => {
const token = await this.props.auth.getAccessToken();
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
'x-forwarded-user': user ? JSON.stringify(user) : ''
}
}
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
client.query({
query: gql`
{
points {
id,
user {
id,
lastName
}
date,
alcohol,
exercise,
diet,
notes
}
}
`
})
.then(result => {
console.log(result);
this.setState({points: result.data.points});
});
}
这是我使用的图书馆列表:
import { ApolloClient } from 'apollo-client';
import { Link } from 'react-router-dom';
import gql from 'graphql-tag';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';
答案 0 :(得分:0)
我也遇到了同样的错误,使用这组库对其进行了修复
import { ApolloClient } from "apollo-client";
import { createHttpLink } from "apollo-link-http";
import { setContext } from "apollo-link-context";
import { InMemoryCache } from "apollo-cache-inmemory";