【发布时间】: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