Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix error:only absolute URLS are supported in react ssr graphql

I'm setting the server side rendering with apollo for set up the graphql in server side but I dont now know how I ran into this problem when ever I tried to use the query in side the one component this error appear in 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)

Please if you now what happen let me know.

Server code

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));
like image 966
Sajjad Hadafi Avatar asked Mar 23 '19 10:03

Sajjad Hadafi


1 Answers

Seems like you have a typo in your url instead of:

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

you need to use:

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

with apollo absolute url means that api url must start with http:// or https://

like image 96
ewief Avatar answered Nov 10 '22 17:11

ewief