gpt4 book ai didi

javascript - 授权后更新标题 authLink react-apollo

转载 作者:行者123 更新时间:2023-11-30 06:50:54 25 4
gpt4 key购买 nike

我正在使用 Github Graphql API。

当我的应用首次加载时,我会让用户去检索一个access_token。这是有效的,但是,该应用程序已经加载,因此我需要在从服务器返回 access_token 后更新授权 header 。我的 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'),
)

最佳答案

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

当您收到 token 时

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

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

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

关于javascript - 授权后更新标题 authLink react-apollo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50118443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com