Сср с Аполлона делает бесконечный цикл - PullRequest
0 голосов
/ 13 мая 2019

У меня такое поведение, которое я не понимаю, когда пытался добавить srr в свой проект. Кажется, есть бесконечный цикл, который рендерится. вот код, который не работает:

server.js

app.use((req, res) => {
    const client = new ApolloClient({
        ssrMode: true,
        // Remember that this is the interface the SSR server will use to connect to the
        // API server, so we need to ensure it isn't firewalled, etc
        link: createHttpLink({
            uri: 'http://localhost:4000/graphql',
            credentials: 'same-origin',
            headers: {
                cookie: req.header('Cookie'),
            },
        }),
        resolvers: {},
        cache: new InMemoryCache(),

    });
    cacheManager.client = client

    const context = {};

    // The client-side App will instead use <BrowserRouter>
    const App = (
        <ApolloProvider client={client}>
            <StaticRouter location={req.url} context={context}>
                <ReactApp />
            </StaticRouter>
        </ApolloProvider>
    );

    // rendering code
    getDataFromTree(App).then(() => {
        // We are ready to render for real
        const content = ReactDOM.renderToString(App);
        const initialState = client.extract();

        const html = <Html content={content} state={initialState} />;

        res.status(200);
        res.send(`<!doctype html>\n${ReactDOM.renderToStaticMarkup(html)}`);
        res.end();
    });
});
const port = process.env.PORT || 4000;
app.listen(port);

А вот проверенный код, который хорошо работал до того, как я начал добавлять специфичный для ssr код:

server.js

app.use('/graphql', auth, setFbToken,
    function (err, req, res, next) {
        if (err.code === 'invalid_token') return next();
        return next(err);
    },
    graphqlHTTP((req, res, graphQLParams) => {
        // console.log('trying if request is authorized (user:', req.user)
        return {
            schema: GraphQlSchema,
            graphiql: true,
            formatError,
            context: {
                user: req.user,
                sessionID: req.sessionID
            }
        }
    }
    ));

App.js

class App extends Component {

    render() {
        if (window != null) {
            return (
                <MuiThemeProvider theme={theme}>
                    <BrowserRouter>
                        <Switch>
                            {routes.map((route) => {
                                const { routeComp: RouteComp, path } = route
                                console.log("adding route : ", route.path)
                                return (
                                    <RouteComp key={path} {...route} />
                                )
                            })}
                        </Switch>
                    </BrowserRouter>
                </MuiThemeProvider>
            );
        } else {
            console.log( "displaying app ", new Error() )
            const history = createMemoryHistory();
            return (
            <MuiThemeProvider theme={theme}>
                <Router history={history}>
                    <Switch>
                        {routes.map((route) => {
                            const { routeComp: RouteComp, path } = route
                            return (
                                <RouteComp key={path} {...route} />
                            )
                        })}
                    </Switch>
                </Router>
            </MuiThemeProvider>
            )
        }
    }
}

В консоли у меня появляется следующее сообщение, которое повторяется снова и снова, но в моем браузере есть только один запрос к серверу:

displaying app  Error:
    at App.render (D:\work\weallyServer\server\src\client/App.js:52:36)
    at processChild (D:\work\weallyServer\server\node_modules\react-dom\cjs\react-dom-server.node.development.js:2959:18)
    at resolve (D:\work\weallyServer\server\node_modules\react-dom\cjs\react-dom-server.node.development.js:2812:5)
    at ReactDOMServerRenderer.render (D:\work\weallyServer\server\node_modules\react-dom\cjs\react-dom-server.node.development.js:3202:22)
    at ReactDOMServerRenderer.read (D:\work\weallyServer\server\node_modules\react-dom\cjs\react-dom-server.node.development.js:3161:29)
    at renderToStaticMarkup (D:\work\weallyServer\server\node_modules\react-dom\cjs\react-dom-server.node.development.js:3661:27)
    at process (D:\work\weallyServer\server\node_modules\react-apollo\react-apollo.cjs.js:1043:20)
displaying app  Error:
    at App.render (D:\work\weallyServer\server\src\client/App.js:52:36)
    at processChild (D:\work\weallyServer\server\node_modules\react-dom\cjs\react-dom-server.node.development.js:2959:18)
    at resolve (D:\work\weallyServer\server\node_modules\react-dom\cjs\react-dom-server.node.development.js:2812:5)
    at ReactDOMServerRenderer.render (D:\work\weallyServer\server\node_modules\react-dom\cjs\react-dom-server.node.development.js:3202:22)
    at ReactDOMServerRenderer.read (D:\work\weallyServer\server\node_modules\react-dom\cjs\react-dom-server.node.development.js:3161:29)
    at renderToStaticMarkup (D:\work\weallyServer\server\node_modules\react-dom\cjs\react-dom-server.node.development.js:3661:27)
    at process (D:\work\weallyServer\server\node_modules\react-apollo\react-apollo.cjs.js:1043:20)

Кроме того, в конфигурации ApolloClient (см. Первый раздел кода), если я не добавляю пустой атрибут resolvers в conf resolvers: {}, , я получаю следующие ошибки, я не знаю, правильно ли ставить пустые резольверы или причина ошибки

Found @client directives in query but no client resolvers were specified. You can now pass apollo-link-state resolvers to the ApolloClient constructor.
requested :  /graphql
graphQl error :  Cannot query field "name" on type "Query".
graphQl error stack:  GraphQLError: Cannot query field "name" on type "Query".
    at Object.Field (D:\work\weallyServer\server\node_modules\graphql\validation\rules\FieldsOnCorrectType.js:64:31)
    at Object.enter (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:332:29)
    at Object.enter (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:383:25)
    at visit (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:250:26)
    at validate (D:\work\weallyServer\server\node_modules\graphql\validation\validate.js:63:22)
    at D:\work\weallyServer\server\node_modules\express-graphql\dist\index.js:139:52
    at process._tickCallback (internal/process/next_tick.js:68:7)
graphQl error :  Unknown directive "client".
graphQl error stack:  GraphQLError: Unknown directive "client".
    at Object.Directive (D:\work\weallyServer\server\node_modules\graphql\validation\rules\KnownDirectives.js:105:29)
    at Object.enter (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:332:29)
    at Object.enter (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:383:25)
    at visit (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:250:26)
    at validate (D:\work\weallyServer\server\node_modules\graphql\validation\validate.js:63:22)
    at D:\work\weallyServer\server\node_modules\express-graphql\dist\index.js:139:52
    at process._tickCallback (internal/process/next_tick.js:68:7)
graphQl error :  Cannot query field "eid" on type "Query".
graphQl error stack:  GraphQLError: Cannot query field "eid" on type "Query".
    at Object.Field (D:\work\weallyServer\server\node_modules\graphql\validation\rules\FieldsOnCorrectType.js:64:31)
    at Object.enter (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:332:29)
    at Object.enter (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:383:25)
    at visit (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:250:26)
    at validate (D:\work\weallyServer\server\node_modules\graphql\validation\validate.js:63:22)
    at D:\work\weallyServer\server\node_modules\express-graphql\dist\index.js:139:52
    at process._tickCallback (internal/process/next_tick.js:68:7)
graphQl error :  Unknown directive "client".
graphQl error stack:  GraphQLError: Unknown directive "client".
    at Object.Directive (D:\work\weallyServer\server\node_modules\graphql\validation\rules\KnownDirectives.js:105:29)
    at Object.enter (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:332:29)
    at Object.enter (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:383:25)
    at visit (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:250:26)
    at validate (D:\work\weallyServer\server\node_modules\graphql\validation\validate.js:63:22)
    at D:\work\weallyServer\server\node_modules\express-graphql\dist\index.js:139:52
    at process._tickCallback (internal/process/next_tick.js:68:7)
graphQl error :  Cannot query field "previewId" on type "Query".
graphQl error stack:  GraphQLError: Cannot query field "previewId" on type "Query".
    at Object.Field (D:\work\weallyServer\server\node_modules\graphql\validation\rules\FieldsOnCorrectType.js:64:31)
    at Object.enter (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:332:29)
    at Object.enter (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:383:25)
    at visit (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:250:26)
    at validate (D:\work\weallyServer\server\node_modules\graphql\validation\validate.js:63:22)
    at D:\work\weallyServer\server\node_modules\express-graphql\dist\index.js:139:52
    at process._tickCallback (internal/process/next_tick.js:68:7)
graphQl error :  Unknown directive "client".
graphQl error stack:  GraphQLError: Unknown directive "client".
    at Object.Directive (D:\work\weallyServer\server\node_modules\graphql\validation\rules\KnownDirectives.js:105:29)
    at Object.enter (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:332:29)
    at Object.enter (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:383:25)
    at visit (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:250:26)
    at validate (D:\work\weallyServer\server\node_modules\graphql\validation\validate.js:63:22)
    at D:\work\weallyServer\server\node_modules\express-graphql\dist\index.js:139:52
    at process._tickCallback (internal/process/next_tick.js:68:7)
graphQl error :  Cannot query field "kind" on type "Query".
graphQl error stack:  GraphQLError: Cannot query field "kind" on type "Query".
    at Object.Field (D:\work\weallyServer\server\node_modules\graphql\validation\rules\FieldsOnCorrectType.js:64:31)
    at Object.enter (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:332:29)
    at Object.enter (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:383:25)
    at visit (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:250:26)
    at validate (D:\work\weallyServer\server\node_modules\graphql\validation\validate.js:63:22)
    at D:\work\weallyServer\server\node_modules\express-graphql\dist\index.js:139:52
    at process._tickCallback (internal/process/next_tick.js:68:7)
graphQl error :  Unknown directive "client".
graphQl error stack:  GraphQLError: Unknown directive "client".
    at Object.Directive (D:\work\weallyServer\server\node_modules\graphql\validation\rules\KnownDirectives.js:105:29)
    at Object.enter (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:332:29)
    at Object.enter (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:383:25)
    at visit (D:\work\weallyServer\server\node_modules\graphql\language\visitor.js:250:26)
    at validate (D:\work\weallyServer\server\node_modules\graphql\validation\validate.js:63:22)
    at D:\work\weallyServer\server\node_modules\express-graphql\dist\index.js:139:52
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:8092) UnhandledPromiseRejectionWarning: Error: Network error: Response not successful: Received status code 400
    at new ApolloError (D:\work\weallyServer\server\node_modules\apollo-client\bundle.esm.js:60:28)
    at QueryManager.<anonymous> (D:\work\weallyServer\server\node_modules\apollo-client\bundle.esm.js:1184:45)
    at step (D:\work\weallyServer\server\node_modules\tslib\tslib.js:133:27)
    at Object.next (D:\work\weallyServer\server\node_modules\tslib\tslib.js:114:57)
    at D:\work\weallyServer\server\node_modules\tslib\tslib.js:107:75
    at new Promise (<anonymous>)
    at Object.__awaiter (D:\work\weallyServer\server\node_modules\tslib\tslib.js:103:16)
    at __awaiter (D:\work\weallyServer\server\node_modules\apollo-client\bundle.esm.js:1147:77)
    at D:\work\weallyServer\server\node_modules\apollo-client\bundle.esm.js:1627:17
    at Array.forEach (<anonymous>)
    at D:\work\weallyServer\server\node_modules\apollo-client\bundle.esm.js:1626:18
    at Map.forEach (<anonymous>)
    at QueryManager.broadcastQueries (D:\work\weallyServer\server\node_modules\apollo-client\bundle.esm.js:1621:22)
    at D:\work\weallyServer\server\node_modules\apollo-client\bundle.esm.js:1127:47
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:8092) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:8092) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Если я удаляю часть ssr, все отлично работает со стороны клиента, поэтому в моих запросах graphql нет ошибок.

Обратите также внимание, что если я заменю повторную процедуру на простой

const App = (
        <ApolloProvider client={client}>
                <div>Hi everybody</div>
        </ApolloProvider>
    );

Цикла нет, и сообщение Привет, все возвращаются клиенту

Вы можете проверить это по этому адресу: https://github.com/ziedHamdi/react-apollo-error-template

Спасибо за вашу помощь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...