您应该有一个身份验证机制,例如登录、注销、检查令牌等功能(auth.js)然后您可以将您的组件包装在包装 Apollo 客户端的高阶组件中。
下面是我使用 Strapi 后端的工作代码。
import { InMemoryCache } from "apollo-cache-inmemory";
import { ApolloClient } from "apollo-client";
import { ApolloLink } from "apollo-link";
import { HttpLink } from "apollo-link-http";
import { setContext } from "@apollo/link-context";
import React from "react";
import auth from "../auth/auth";
const httpLink = new HttpLink({
uri: process.env.REACT_APP_API_URL,
cors: false,
});
const authLink = setContext((_, { headers }) => {
const token = auth.getToken() || null;
return token
? {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
},
}
: null;
});
export const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});
const AppProvider = ({ children }) => {
return <ApolloProvider client={client}>{children}</ApolloProvider>;
};
auth.js 用于获取/设置凭据:
import { isEmpty } from "lodash";
const TOKEN_KEY = "jwtToken";
const USER_INFO = "userInfo";
const parse = JSON.parse;
const stringify = JSON.stringify;
const auth = {
clear(key) {
if (localStorage && localStorage.getItem(key)) {
return localStorage.removeItem(key);
}
if (sessionStorage && sessionStorage.getItem(key)) {
return sessionStorage.removeItem(key);
}
return null;
},
clearAppStorage() {
if (localStorage) {
localStorage.clear();
}
if (sessionStorage) {
sessionStorage.clear();
}
},
clearToken(tokenKey = TOKEN_KEY) {
return auth.clear(tokenKey);
},
clearUserInfo(userInfo = USER_INFO) {
return auth.clear(userInfo);
},
get(key) {
if (localStorage && localStorage.getItem(key)) {
return parse(localStorage.getItem(key)) || null;
}
if (sessionStorage && sessionStorage.getItem(key)) {
return parse(sessionStorage.getItem(key)) || null;
}
return null;
},
getToken(tokenKey = TOKEN_KEY) {
return auth.get(tokenKey);
},
getUserInfo(userInfo = USER_INFO) {
return auth.get(userInfo);
},
set(value, key, isLocalStorage) {
if (isEmpty(value)) {
return null;
}
if (isLocalStorage && localStorage) {
return localStorage.setItem(key, stringify(value));
}
if (sessionStorage) {
return sessionStorage.setItem(key, stringify(value));
}
return null;
},
setToken(value = "", isLocalStorage = false, tokenKey = TOKEN_KEY) {
return auth.set(value, tokenKey, isLocalStorage);
},
setUserInfo(value = "", isLocalStorage = false, userInfo = USER_INFO) {
return auth.set(value, userInfo, isLocalStorage);
},
};
export default auth;