我使用的是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'),
)发布于 2018-05-02 00:39:31
将令牌存储在客户端上的某个位置。localStorage将是一个很好的选择。
当您收到令牌时
...
let token = body.token
localStorage.setItem('token')您传递给setContext的函数将在每次请求时执行,因此即使在应用程序初始加载之后,您也可以从localStorage读取令牌。
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
authorization: `Bearer ${localStorage.getItem('token')}`,
}
}
})https://stackoverflow.com/questions/50118443
复制相似问题