我必须处理每个请求的react js中的身份验证错误。那么,如何全局处理身份验证错误?
import {
ApolloClient,
ApolloLink,
InMemoryCache,
HttpLink
} from "apollo-boost";
import fetch from "isomorphic-unfetch";
let apolloClient = null;
if (!process.browser) {
global.fetch = fetch;
}
const httpLink = new HttpLink({
uri: "http://localhost/suitecrm/process.php"
});
const authLink = new ApolloLink((operation, forward) => {
let token = "";
if (
localStorage.getItem("token") != null &&
localStorage.getItem("token") != ""
) {
token = localStorage.getItem("token");
}
operation.setContext({
headers: {
"Content-Type": "application/json",
authorization: token ? `${token}` : ""
}
});
return forward(operation);
});
export default function initApollo(initialState) {
if (!apolloClient) {
apolloClient = new ApolloClient({
link: authLink.concat(httpLink), // Chain it with the HttpLink
cache: new InMemoryCache()
});
}
return apolloClient;
我正在使用以上文件进行调用graphQL查询和变异。
谢谢
答案 0 :(得分:0)
您可以使用apollo-link-error包中的onError
来全局获取错误。 Apollo-Boost还包括此导出。
import { onError } from 'apollo-link-error';
const errorLink = onError(({ graphQLErrors, networkError, operation }) => {
if (graphQLErrors)
graphQLErrors.map(({ message, path }) =>
console.error(`[GraphQL error]: Message: ${message}, Operation: ${operation.operationName}, Path: ${path}`),
);
if (networkError) console.error(`[Network error]: ${networkError}`);
});
...
apolloClient = new ApolloClient({
link: ApolloLink.from([errorLink, authLink, httpLink]),
cache: new InMemoryCache()
});