Apollo graphql设置头到authmiddleware不起作用 [英] Apollo graphql setting header to authmiddleware not working

查看:111
本文介绍了Apollo graphql设置头到authmiddleware不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用react-native和apollo客户端,如果我尝试通过存储在AsyncStorage中的jwt设置标头,则似乎无法正常工作.
其他不需要头的解析器也可以很好地工作.我的代码如下所示.

I am using react-native and apollo client and if I try to set header by jwt stored in AsyncStorage, it seems not working.
Other resolvers which doesn't need header works very well. My code is like below.

import { ApolloClient } from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import { ApolloLink } from "apollo-link";
import { createHttpLink } from "apollo-link-http";
import AsyncStorage from "@react-native-community/async-storage";

const cache = new InMemoryCache();

const getToken = async () => {
  const token = await AsyncStorage.getItem("jwt");

  if (token) {
    return token;
  } else {
    return null;
  }
};

const httpLink = new createHttpLink({
  uri: ""
});

const authLink = new ApolloLink((operation, forward) => {
  operation.setContext({
    headers: {
      "X-JWT": getToken()
      // this is where I set headers by getToken function
      // If I change function getToken to real token in string type, it works then
    }
  });

  return forward(operation);
});

const client = new ApolloClient({
  cache: cache,
  link: authLink.concat(httpLink)
});

export default client;

就像我在代码中评论的那样,调用getToken函数无法按预期工作.我想我应该对异步和等待有更多的了解,但是我不了解真正的问题是什么.

Like I commented in the code, calling getToken function is not working what I expected. I think I should have more knowledge of async and await, but I don't get it what is the real problem.

我从控制台收到的错误消息是 jwt格式错误.请让我知道如何解决此问题

The error message I get from console is jwt malformed. Please let me know how to fix this problem

推荐答案

尝试直接使用 setContext

import { ApolloClient } from "apollo-client";
import { createHttpLink } from "apollo-link-http";
import { setContext } from "apollo-link-context";
import { InMemoryCache } from "apollo-cache-inmemory";
import AsyncStorage from "@react-native-community/async-storage";

const httpLink = createHttpLink();

const authLink = setContext(async (_, { headers }) => {
  const token = await AsyncStorage.getItem("jwt");

  return {
    headers: {
      ...headers,
      "X-JWT": token || null
    }
  };
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

export default client;

这篇关于Apollo graphql设置头到authmiddleware不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆