1

I have an test application running in a EC2 in Amazon. Its a react app, with Apollo, GraphQl and Sequelize. It works perfect through google chrome of my notebook, but when I open the page from a Mobile Phone with Android this error apears

Error Network error: Failed to fetch
localhost:9000/graphql:1 Failed to load resource: net::ERR_CONNECTION_REFUSED

Version of "react-apollo": "^2.5.6"

My Client index

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import {RootSession} from './App';
import * as serviceWorker from './serviceWorker';
import ApolloClient, { InMemoryCache } from 'apollo-boost';
import { ApolloProvider } from 'react-apollo';


const client = new ApolloClient({
    uri: "http://localhost:9000/graphql",
    fetchOptions:{
      credentials: 'include'
    },
    request: operation =>{
      const token = localStorage.getItem('token');
      operation.setContext({
        headers:{
          authorization:token ? token : null,
        }
      })
    },
    cache: new InMemoryCache({
      addTypename:false
    }),
    onError: ({networkError,graphQLErrors,response,operation,forward})=>{
      if (networkError){
        console.log("network",networkError) ;
      }

      if (graphQLErrors){
        for(let err of graphQLErrors){
          switch (err.extensions.code){
            case 'UNAUTHENTICATED':                           
              localStorage.removeItem('token');  
          }
        }
      }
    }
  });


ReactDOM.render(
<ApolloProvider client={client}> 
    <RootSession />
</ApolloProvider>, 
document.getElementById('root'));
serviceWorker.unregister();

My Server Index

import express from 'express';
import { ApolloServer, AuthenticationError } from 'apollo-server-express';
import { typeDefs } from './data/schema';
import { resolvers } from './data/resolvers';
import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';
import db from "./models";

dotenv.config({path:'variables.env'});


const app = express();

//const cors = require('cors');
//app.use(cors());
const addToken = async (req) =>{

}
const server=  new ApolloServer({
    typeDefs,
    resolvers,

    context:async ({req})=>{
        const token = req.headers['authorization'];
        let currentUser = null;

        if (token !== 'null' && token !== 'undefined' && token !== '' && token !== null && token !== undefined){
            try{           

                currentUser = await jwt.verify(token,process.env.SECRET);    
                req.currentUser = currentUser;

            }catch (err){
                throw new AuthenticationError('Your session expired. Sign in again.');    
            }  
        }
      return {user:currentUser,db}  ;
    }
});

server.applyMiddleware({app});
app.listen({port:9000},()=> console.log(`Server Corriendo http://localhost:9000${server.graphqlPath}`));

In my server index, I also tried

const cors = require('cors');
app.use(cors());

but I dont have luck

Im Serving the Client with serve -s build (serve npm package) Im Serving the Server with npm start

What about, that this line could break in a mobile phone? (localhost)

 const client = new ApolloClient({
        uri: "http://localhost:9000/graphql",
emmanuel sio
  • 1,935
  • 3
  • 24
  • 26
  • Can you share what version of `react-apollo` you're using. Also, do you know if the browser in question support fetch? If not you might need to address through polyfill. (https://www.apollographql.com/docs/link/links/http/#fetch) – dusthaines Jul 25 '19 at 03:49
  • Yes, its "react-apollo": "^2.5.6". the browser is a new one – emmanuel sio Jul 25 '19 at 03:52
  • perhaps an issue related to a header value of `null`? (https://github.com/apollographql/react-apollo/issues/763#issuecomment-390935309) Is `authorization: token` always defined in all of your test scenarios? – dusthaines Jul 25 '19 at 04:07
  • No, its not that. I think that is something about how I m serving the client code, but I dont know what could be – emmanuel sio Jul 25 '19 at 11:49

1 Answers1

2

I believe the problem is that you are using localhost as your server URL. That works when your browser is running on the same machine that is hosting the servers, but that's not the case anymore when you are running the client on a mobile device. Try using the local or public IP of the machine being used to host the server in your client URL, like http://192.168.0.8:9000/.

This answer has an explanation for how to get your local IP address on linux: https://stackoverflow.com/a/13322549/11804768

  • The error was in the index client, where I used localhost. I change it for the public ip of server with the correct port, and now it works – emmanuel sio Jul 26 '19 at 12:02