我遇到一个问题,当我从'apollo-boost',用{ ApolloClient }
向我的后端服务器发送自定义标头时,我不能指定 URI ,< br />
因此,我不得不改用'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时,它再次起作用。
任何帮助都将不胜感激!
答案 0 :(得分:1)
不确定100%,但是我认为错误出在这里:
const store = JSON.parse(sessionStorage.getItem('interdevs-data'));
const token = store.token;
如果没有键为interdevs-data
的商品,商店将为空。
我认为您可以通过以下方法解决此问题:
const store = JSON.parse(sessionStorage.getItem('interdevs-data'));
const token = store ? store.token : null;
答案 1 :(得分:0)
了解如何使用apollo-boost设置身份验证标头
const client = new ApolloClient({
uri: 'http://localhost:3001/graphql',
request: operation => {
const ssData = JSON.parse(sessionStorage.getItem('data'));
operation.setContext({
headers: {
authorization: ssData ? `Bearer ${ssData.token}` : ''
}
});
}
});