3

使用 react on rails 到服务器端渲染 apollo 和 react router v4 时出现以下错误:Error: unable to locate global object。我试图实现以下但没有奏效:

ApolloClientServer.js

import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';
import fetch from 'node-fetch';

const httpLink = createHttpLink({
  uri: '/graphql',
  fetch,
  clientState: {
    defaults: {},
  }
});

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

export const client = new ApolloClient({
  ssrMode: true,
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

服务器.js:

import React from 'react';
import { Provider } from 'react-redux';
import { StaticRouter } from 'react-router';
import adminStore from '../redux/store';
import AdminMain from './AdminMain';
import { ApolloProvider } from 'react-apollo';
import { client } from '../utils/ApolloClientServer';

export default (_props, railsContext) => {
  ....

  return (
    <ApolloProvider client={client}>
      <StaticRouter
        location={location}
        context={context}
      >
        <AdminMain />
      </StaticRouter>
    </ApolloProvider>
  );
};

是否有我缺少的配置或者我需要导入另一个库?

4

0 回答 0