首页 > 解决方案 > 授权后更新标头 authLink react-apollo

问题描述

我正在使用 Github Graphql API。

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

// 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'),
)

标签: javascriptreactjsgithub-apireact-apollo

解决方案


将令牌存储在客户端的某处。localStorage将是一个不错的选择。

当您收到令牌时

...
let token = body.token
localStorage.setItem('token')

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

const authLink = setContext((_, { headers }) => {
  return {
    headers: {
      ...headers,
      authorization: `Bearer ${localStorage.getItem('token')}`,
    }
  }
})

推荐阅读