Mat*_*aly 2 jwt apollo graphql
我正在使用Laravel应用程序,该应用程序在客户端使用React和Redux,以及React预设和Mix。我决定尝试使用API的GraphQL,而不是通常的REST API方法,到目前为止,它的工作正常。但是,我现在陷入困境。
我将Apollo用作HTTP客户端,因为它是为与GraphQL一起使用而构建的。过去,我曾使用JWT Auth来保护API,因此自然而然也选择了这种方法,因为实现只是添加适当的标头的一种情况。我遵循了有关使用Apollo设置标题的说明,但是没有设置标题。这是有问题的JS文件:
import LinkList from './components/LinkList';
import React from 'react';
import ReactDOM from 'react-dom';
import {Container} from './container';
import {createStore} from 'redux';
import reducer from './reducer';
import {Provider} from 'react-redux';
import {fromJS} from 'immutable';
import ApolloClient from 'apollo-boost';
import gql from 'graphql-tag';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';
const httpLink = createHttpLink({
uri: window.initialData.graphql_route
});
const authLink = setContext((_, { headers }) => {
const token = window.initialData.jwt;
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
}
}
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
client.query({
query: gql`{
links {
id
title
link
}}`
}).then(result => console.log(result));
const store = createStore(
reducer,
fromJS(window.initialData),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
if (document.getElementById('list')) {
ReactDOM.render(
<Provider store={store}>
<Container />
</Provider>,
document.getElementById('list')
);
}
Run Code Online (Sandbox Code Playgroud)
我window.initialData
在视图中进行填充,其中包含必要的数据,其中包括JWT令牌window.initialData.jwt
。在定义中设置断点authLink
无济于事,这意味着它永远不会被调用。
知道发生了什么问题吗?我已经非常仔细地遵循了文档中的示例,因此我想到的只是它们可能过时了。
Ale*_*noz 11
您正在使用来自“ apollo-boost”的ApolloClient,但令牌配置是针对另一个ApolloClient,即“ apollo-client”的{ApolloClient}。
如果要使用apollo-boost中的ApolloClient保存令牌:
const client = new ApolloClient({
uri: ...,
request: async operation => {
const token = localStorage.getItem('token');
operation.setContext({
headers: {
authorization: token ? `Bearer ${token}` : ''
}
});
}
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4020 次 |
最近记录: |