![](/img/trans.png)
[英]updateQueries after GraphQL mutation not working with the Apollo client
[英]GraphQL mutation not being sent to request when using Apollo client?
我遇到了一個問題,當使用來自'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 時,它又可以工作了。
非常感謝任何幫助!
不是100%肯定,但我認為錯誤在於:
const store = JSON.parse(sessionStorage.getItem('interdevs-data'));
const token = store.token;
如果沒有鍵interdevs-data
的項目,則store 將為 null 。
我認為你可以通過這樣做來解決它:
const store = JSON.parse(sessionStorage.getItem('interdevs-data'));
const token = store ? store.token : null;
了解如何使用 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}` : ''
}
});
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.