Я использую 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'),
)