emmanuel sio
emmanuel sio

Reputation: 1955

React JS + Apollo client query error: “Network error: Failed to fetch” . when call from mobile phone

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",

Upvotes: 1

Views: 10817

Answers (1)

Jason Paulos
Jason Paulos

Reputation: 84

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

Upvotes: 2

Related Questions