首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在GraphQL后端ReactQL中为每个阿波罗添加一个头

如何在GraphQL后端ReactQL中为每个阿波罗添加一个头
EN

Stack Overflow用户
提问于 2018-01-06 12:20:23
回答 1查看 257关注 0票数 1

我想向GraphQL后端的每个请求中添加一个授权头。我使用的是Remotbackend。

阿波罗文档中有一个如何添加标题的示例:https://www.apollographql.com/docs/react/recipes/authentication.html#Header

代码语言:javascript
复制
import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';

const httpLink = createHttpLink({
  uri: '/graphql',
});

const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = localStorage.getItem('token');
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : null,
    }
  }
});

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

但是我该如何用ReactQL来完成这个任务呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-06 12:58:47

在ReactQL的回购示例中

https://github.com/reactql/example-auth

提到了一种方法:

代码语言:javascript
复制
  config.setApolloNetworkOptions({
    credentials: 'include',
  });

  config.addApolloMiddleware((req, next) => {
    const token = 'the_token'
    req.options.headers = {
      ...req.options.headers,
      authorization: token
    };
    next();
  });

这会将标题添加到每个请求!

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48127267

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档