首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >授权后更新headers react-apollo

授权后更新headers react-apollo
EN

Stack Overflow用户
提问于 2018-05-01 22:36:25
回答 1查看 1.1K关注 0票数 3

我使用的是Github Graphql API。

当我的应用程序第一次加载时,我会让用户去获取一个access_token。这是有效的,但是,应用程序已经加载,所以我需要更新授权标头,一旦从服务器返回一个access_token。我的index.js文件中的代码如下所示

代码语言:javascript
复制
// request to get access_token
request.post({
  url: 'http://localhost:8080/authorize',
  body: JSON.stringify({ code: '123456789' })
}, function(error, response, body){ 
   // token is retrieved at this point, 
   // but the code to set up the Apollo-client 
   // has already been executed.
  let token = body.token
});

// all the code below is executed before the access_token above is returned
const httpLink = createHttpLink({
  uri: 'https://api.github.com/graphql',
})

const authLink = setContext((_, { headers }) => {
  return {
    headers: {
      ...headers,
      authorization: `Bearer ${process.env.REACT_APP_GITHUBTOKEN}`,
    }
  }
})

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

ReactDOM.render(
  <BrowserRouter>
    <ApolloProvider client={ client }>
      <App />
    </ApolloProvider>
  </BrowserRouter>,
  document.getElementById('root'),
)
EN

回答 1

Stack Overflow用户

发布于 2018-05-02 00:39:31

将令牌存储在客户端上的某个位置。localStorage将是一个很好的选择。

当您收到令牌时

代码语言:javascript
复制
...
let token = body.token
localStorage.setItem('token')

您传递给setContext的函数将在每次请求时执行,因此即使在应用程序初始加载之后,您也可以从localStorage读取令牌。

代码语言:javascript
复制
const authLink = setContext((_, { headers }) => {
  return {
    headers: {
      ...headers,
      authorization: `Bearer ${localStorage.getItem('token')}`,
    }
  }
})
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50118443

复制
相关文章

相似问题

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