我正在学习如何使用 graphql 和 apollo 制作 React 应用程序。
首先,我能够进行一个从服务器返回帖子的查询:
(在我的 app.js 文件中)
<Query
query={gql`
{
feed {
id
title
}
}
`}
>
{({ loading, error, data }) => {
if (loading) return <p>...loading...</p>;
if (error) return <p>ERROR ! Try reloading</p>;
return data.feed.map(feed => (
<div key={feed.id}>{`Title: ${feed.title}`}</div>
));
}}
</Query>
);
成功了。
然后,我想要进行需要授权的查询和突变。由于服务器需要 header ,我遵循 this recipe .
(在我的 index.js 文件中)
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import ApolloClient from 'apollo-boost';
import { ApolloProvider } from 'react-apollo';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import registerServiceWorker from './registerServiceWorker';
import App from './App/App';
const GRAPHQL_API_URI = 'https://shopozor-server.herokuapp.com/';
const httpLink = createHttpLink({
uri: GRAPHQL_API_URI,
});
const authLink = setContext((_, { headers }) => {
// get the authentication token from local storage if it exists
const token = localStorage.getItem('token');
// 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()
});
ReactDOM.render(
<ApolloProvider client={client}>
<BrowserRouter>
<App />
</BrowserRouter>
</ApolloProvider>,
document.getElementById('root')
);
registerServiceWorker();
然后我之前的查询就不再起作用了。我收到了错误负载而不是帖子。并且控制台中写入了一条错误消息:
[Network error]: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
调试后发现引用的index.js文件位于apollo-boost模块中,该模块以
开头"use strict"
另外我发现
createHttpLink({
uri: GRAPHQL_API_URI,
});
没有使用我提供的链接,而是使用了空字符串。
现在我没有主意了。有人可以帮我解决这个问题吗?
谢谢
最佳答案
我的一个 friend 解决了这个问题。我正在使用
import ApolloClient from 'apollo-boost';
而不是
import { ApolloClient } from 'apollo-client';
这是具有相同名称的不同包。我曾以为 apollo-boost 只是使用 apollo-client 的 bundle ,但事实并非如此。 如果我做出这个微小的改变,它就会起作用。
apollo-boost 还不支持所有 apollo 功能,即使它提供了开箱即用的工作客户端,我也不能将它用于所有功能。看看this article .
关于reactjs - 使用 header 配方的 Apollo 授权不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49852961/