[英]update headers authLink react-apollo after authorization
I am using the Github Graphql API. 我正在使用Github Graphql API。
When my app first loads I send the user off to retrieve an access_token
. 当我的应用程序首次加载时,我将用户送去检索access_token
。 This is working, however, the app has already loaded so I need to update the authorization headers once an access_token has been returned from the server. 这正在工作,但是应用程序已经加载,因此一旦从服务器返回了access_token,我就需要更新授权标头。 My code in my index.js
file looks like the following 我在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'),
)
Store the token somewhere on the client. 将令牌存储在客户端上的某个位置。 localStorage
would be a good option. localStorage
将是一个不错的选择。
When you receive the token 当您收到令牌时
...
let token = body.token
localStorage.setItem('token')
The function you pass to setContext
gets executed on every request so you can read the token from localStorage
even after the initial app load. 传递给setContext
的函数将在每个请求上执行,因此即使在初始应用加载后,您也可以从localStorage
读取令牌。
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
authorization: `Bearer ${localStorage.getItem('token')}`,
}
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.