【发布时间】:2018-10-17 01:49:17
【问题描述】:
我正在开发一个 Laravel 应用程序,该应用程序在客户端使用 React 和 Redux,并带有 React 预设和 Mix。我决定为 API 尝试 GraphQL,而不是通常的 REST API 方法,到目前为止它运行良好。但是,我现在卡住了。
我使用 Apollo 作为我的 HTTP 客户端,因为它是为使用 GraphQL 而构建的。过去我使用JWT Auth 来保护API,所以我自然也采用了这种方法,因为实现只是添加适当标头的一个例子。我关注了the instruction on setting headers with 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')
);
}
我在视图中填充window.initialData,其中包含必要的数据,包括作为window.initialData.jwt 的JWT 令牌。在authLink 的定义中设置断点没有任何作用,意味着它永远不会被调用。
知道出了什么问题吗?我已经非常密切地遵循文档中的示例,所以我能想到的只是它们可能已经过时了。
【问题讨论】: