我正在開發一個需要身份驗證才能創建帖子的應用程式,因此我創建了 2 個物件,httpLink(當前鏈接到我的后端)和 authLink(執行以 Bearer 令牌形式傳遞標頭的功能。
這是我處理這些東西的 apollo-client.js 片段
import { ApolloClient, createHttpLink, InMemoryCache } from "@apollo/client";
import { setContext } from "@apollo/client/link/context";
const httpLink = createHttpLink({
uri:"http://localhost:5000"
});
const authLink = setContext(()=>{
if (typeof window !== 'undefined') {
token = localStorage.getItem('jwtToken');
}
return {
headers:{
Authorization: token ? `Bearer ${token}` : "",
}
}
})
const uri = authLink.concat(httpLink);
const client = new ApolloClient({
link: uri ,
cache: new InMemoryCache(),
});
export default client;
現在,如果我嘗試使用 authLink.concat(httpLink),我會收到未定義令牌的錯誤,但在開發工具>應用程式>localStorage 上,它顯示令牌仍然有效。
我也收到一個錯誤,“SyntaxError: Unexpected token < in JSON at position 0”,但我無法重現這一點。
通常,它應該顯示一些我手動插入到資料庫中的帖子,而不是錯誤
uj5u.com熱心網友回復:
看起來您token在初始化之前分配了值。請嘗試將其更新為:
const authLink = setContext(()=>{
var token; <--- Initialize the variable token
if (typeof window !== 'undefined') {
token = localStorage.getItem('jwtToken');
}
return {
headers:{
Authorization: token ? `Bearer ${token}` : "",
}
}
})
uj5u.com熱心網友回復:
您好,您可以這樣做,檔案-> https://www.apollographql.com/docs/react/networking/advanced-http-networking/
const App = () => {
const token = "your token"
const httpLink = new HttpLink({ uri: "your endpoint" });
const authMiddleware = new ApolloLink((operation, forward) => {
// add the authorization to the headers
operation.setContext({
headers: {
authorization: token,
},
});
return forward(operation);
});
const graphQLClient = new ApolloClient({
link: concat(authMiddleware, httpLink),
});
return (
<ApolloProvider client={graphQLClient}>
<YourApp />
</ApolloProvider>
);
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/406422.html
標籤:
