【发布时间】:2020-01-17 10:45:12
【问题描述】:
我必须在每个请求的 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 查询和变异。
谢谢
【问题讨论】:
标签: reactjs react-apollo