React JS + Apollo客户端查询错误:“网络错误:无法获取”。从手机拨打电话时

时间:2019-07-24 21:31:50

标签: node.js reactjs graphql apollo

我有一个运行在Amazon EC2中的测试应用程序。它是一个带有Apollo,GraphQl和Sequelize的react应用。通过我的笔记本电脑的chrome浏览器,它可以完美运行,但是当我从使用Android的手机打开网页时,此错误消失了

错误网络错误:无法获取
localhost:9000 / graphql:1无法加载资源:net :: ERR_CONNECTION_REFUSED

“反应阿波罗”版本:“ ^ 2.5.6”

我的客户索引

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();

我的服务器索引

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}`));

在服务器索引中,我也尝试过

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

但是我没有运气

Im使用serve -s build为客户服务(serve npm软件包) 我通过npm start为服务器提供服务

该行可能会在手机中中断吗? (本地主机)

 const client = new ApolloClient({
        uri: "http://localhost:9000/graphql",

1 个答案:

答案 0 :(得分:1)

我相信问题是您使用localhost作为服务器URL。当您的浏览器在托管服务器的同一台计算机上运行时,这种方法就可以工作,但在移动设备上运行客户端时,情况就不再如此。尝试在客户端URL中使用用于托管服务器的计算机的本地或公共IP,例如http://192.168.0.8:9000/

此答案说明了如何在linux上获取本地IP地址:https://stackoverflow.com/a/13322549/11804768