web-dev-qa-db-ja.com

エラーの修正方法:React SSR GraphQlではサポートされている絶対URLのみがサポートされています。

サーバー側でGraphQlをセットアップするためのApolloでサーバー側のレンダリングを設定していますが、この問題に照会しようとしたときにこの問題にどのように実行されるかがわかりません。このエラーがCLIに表示されます。

(node:4440) UnhandledPromiseRejectionWarning: Error: Network error: Only absolute URLs are supported
at new ApolloError (G:\Project\node_modules\apollo-client\bundle.umd.js:59:32)
    at QueryManager.<anonymous> (G:\Project\node_modules\apollo-client\bundle.umd.js:13:49)
 _

あなたが今何をしても私に知らせてください。

サーバーコード

import React  from 'react'
import routes from '../../client/Routes'

import {StaticRouter} from 'react-router-dom'
import {Provider} from 'react-redux'
import {renderRoutes} from 'react-router-config'
import {AES} from 'crypto-js';
import {Helmet} from "react-helmet";
import serialize from 'serialize-javascript' ;

import  ApolloClient from 'apollo-client';
import { ApolloProvider, renderToStringWithData  } from 'react-apollo';
import { InMemoryCache } from "apollo-cache-inmemory";
import { ApolloLink } from 'apollo-link';
import { errorLink , queryOrMutationLink , getCircularReplacer } from './links';

import fetch from 'node-fetch';

export default async(req,store,context)=>{
    const links = [errorLink,queryOrMutationLink({
        fetch,
        uri: 'http:localhost:3000/api/graphql',
    })]
    const client = new ApolloClient({
        ssrMode: true,
        link:ApolloLink.from(links),
        cache: new InMemoryCache()
    });
    const component = (
        <ApolloProvider client={client}>
            <Provider store={store}>
                <StaticRouter location={req.path} context={context}>
                    {renderRoutes(routes)}
                </StaticRouter>
            </Provider>
        </ApolloProvider>
    )
    return renderToStringWithData(component).then(content=>{
        let serializedStore = serialize(store.getState())
        let hashedUsersList = AES.encrypt(serializedStore, 'secret key 123');
        const helmet        = Helmet.renderStatic();
        return `
            <html>
                <head>
                    ${helmet.title.toString()}
                    ${helmet.meta.toString()}
                    ${helmet.link.toString()}
                    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css">
                    <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
                    <script>window.INITIAL_STATE = ${JSON.stringify(hashedUsersList, getCircularReplacer())}</script>
                </head>
                <body>
                    <div id="root">${content}</div>
                    <script src="/public-bundle.js"></script>
                    <script>window.__APOLLO_STATE__=${JSON.stringify(client.extract(),getCircularReplacer())}</script>
                </body>
            </html>`
    })
}
 _

import React from 'react';
import {hydrate}from 'react-dom';

//-----------Redux
import {Provider} from 'react-redux';
import {createStore, applyMiddleware,compose} from 'redux';
import thunk from 'redux-thunk';
import {AES,enc,} from 'crypto-js'
import axios from 'axios'
//-----------Router
import {BrowserRouter} from 'react-router-dom';
import routes from './Routes';
import {renderRoutes} from 'react-router-config'

//-----------Internal_import
import reducers from './store/reducers';

//-----------GraphQL[APOLLO_CLIENT]
import ApolloClient       from 'apollo-client';
import { InMemoryCache }  from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';
import { ApolloProvider } from 'react-apollo';
import {fetch} from 'node-fetch';

const client = new ApolloClient({
    connectToDevTools: true,
    link: createHttpLink({
        uri: 'http:localhost:3000/api/graphql',
        credentials:'same-Origin'
    }),
    cache: new InMemoryCache({dataIdFromObject:o=>o.id}).restore(window.__APOLLO_STATE__),
})

const axiosInstance = axios.create({baseURL: '/api'});
const composeEnhancers = typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
const enhancer = composeEnhancers(applyMiddleware(thunk.withExtraArgument(axiosInstance)));

let DecryptUsersList  = AES.decrypt(window.INITIAL_STATE, 'secret key 123');
let UsersList_State = JSON.parse(DecryptUsersList.toString(enc.Utf8))

const store = createStore(reducers,UsersList_State,enhancer)

hydrate(
    <ApolloProvider client={client}>
        <Provider store={store}>
            <BrowserRouter>
                {renderRoutes(routes)}
            </BrowserRouter>
        </Provider>
    </ApolloProvider>
    ,document.querySelector('#root')
)

 _
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import {connect} from 'react-redux';
import {graphql} from 'react-apollo';
import gql from 'graphql-tag';
const Header = (props)=>{
  console.log(props)
  const renderButtons=()=>{
    if (props.user) {
      return (
        <div>
          <li><Link to="/admins">Admins</Link></li>
          <li><a href="/api/logout">Logout</a></li>
        </div>
      );
    } else {
      return (
        <div>
          <li>
            <Link to="/users">Users</Link>
          </li>
          <li>
            <Link to="/admins">Admins</Link>
          </li>
          <li>
            <Link to="/Signin">SignIn</Link>
          </li>
          <li>
            <Link to="/Signup">SignUp</Link>
          </li>
          <li>
            <a href="/api/auth/google">Login via google</a>
          </li>
        </div>
      );
    }
  }
    return (
      <nav>
        <div className="nav-wrapper">
          <Link to="/" className="brand-logo left">
            Home
          </Link>
          <ul className="right">
            {renderButtons()}
          </ul>
        </div>
      </nav>
    );
}

const query = gql`
{
    user{
      id
      email
      name
    }
}
`
const mapStateToProps =({auth})=>({user:auth.user})
export default connect(mapStateToProps,null)(graphql(query)(Header));
 _
5
Sajjad Hadafi

URLには代わりにタイプミスがあるようです。

uri: 'http:localhost:3000/api/graphql',

使用する必要があります。

uri: 'http://localhost:3000/api/graphql',

apollo Absolute URLを使用すると、API URLはhttp://またはhttps://から始める必要があることを意味します。

2
ewief