如何将我的授权 Header 与 httpLink 连接起来?使用 Apollo 客户端和 Next Js

How Do I concatenate my Authorization Header with httpLink? Using Apollo Client and Next Js

我正在开发一个需要身份验证才能创建帖子的应用程序,所以我制作了 2 objects、httpLink(当前链接到我的后端)和 authLink(执行功能以不记名令牌的形式传递 header。

这是我的 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),我会收到令牌未定义的错误,但在 Dev tools>Application>localStorage 上,它显示令牌仍然有效。

我也收到了一个错误“SyntaxError: Unexpected token < in JSON at position 0”,但我无法重现这个错误。

通常情况下,它应该显示一些我手动插入到数据库中的帖子而不是错误

您好,您可以这样做,文档 -> 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>
  );
};