【问题标题】:How Do I concatenate my Authorization Header with httpLink? Using Apollo Client and Next Js如何将我的授权标头与 httpLink 连接?使用 Apollo 客户端和 Next Js
【发布时间】:2022-01-06 10:56:12
【问题描述】:

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

这是我处理这些东西的 apollo-client.js 的 sn-p

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

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

【问题讨论】:

    标签: reactjs authentication graphql next.js apollo


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2017-08-31
      • 2019-07-01
      • 2020-08-13
      • 1970-01-01
      • 2020-01-20
      • 1970-01-01
      • 2020-06-12
      • 2021-01-04
      • 1970-01-01
      相关资源
      最近更新 更多