javascript - 授权后更新标头 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'),
)
解决方案
将令牌存储在客户端的某处。localStorage
将是一个不错的选择。
当您收到令牌时
...
let token = body.token
localStorage.setItem('token')
您传递给的函数会在每个请求上执行,因此即使在初始应用程序加载之后setContext
您也可以从中读取令牌。localStorage
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
authorization: `Bearer ${localStorage.getItem('token')}`,
}
}
})
推荐阅读
- c++ - 复制和交换习语与在复制构造函数中调用复制赋值运算符
- postman - 无法解析授权标头
- selenium - 无需编码的测试人员的自动化测试
- r - R中计算曲面下体积的方法
- powerbi - 3 个表之间的 PowerBI AND/OR 函数
- jestjs - 使用 jest 的 automock 时可以恢复原始功能吗?
- java - 如何在某个字段上处理不同的 JSON 响应类型?
- powershell - 使用Powershell仅打印Windows目录中的文件名?
- c - 在不使用 C 标准库中可用的其他函数的情况下将小写字符数组转换为大写字符数组的 C 程序
- java - Python Jpype 在 JAR 文件中看不到 Java 类