React Native Apollo 错误:“网络错误:网络请求失败”

lin*_*hnh 6 networking android apollo graphql react-native

在 IOS 上,应用程序运行正常。但在 Android 上,我收到此错误。这是我在客户端和服务器中的配置。请帮忙!

错误: 错误图像

这是客户端的配置:

import ApolloClient, { createNetworkInterface } from 'apollo-client';
import { SubscriptionClient, addGraphQLSubscriptions } from 'subscriptions-transport-ws';

const networkInterface = createNetworkInterface({ uri: 'http://localhost:3000/graphql' });

const wsClient = new SubscriptionClient('ws://localhost:3000/subscriptions', {
  reconnect: true,
});

const networkInterfaceWithSubscriptions = addGraphQLSubscriptions(
  networkInterface,
  wsClient,
);

export const client = new ApolloClient({
  networkInterface: networkInterfaceWithSubscriptions,
});
Run Code Online (Sandbox Code Playgroud)

这是服务器上的配置:

import express from 'express';
import {
  graphqlExpress,
  graphiqlExpress,
} from 'graphql-server-express';
import bodyParser from 'body-parser';
import cors from 'cors';
import { execute, subscribe } from 'graphql';
import { createServer } from 'http';
import { SubscriptionServer } from 'subscriptions-transport-ws';
import { schema } from './schema';

const PORT = 3000;
const server = express();

server.use('*', cors({ origin: 'http://localhost:8081' }));
server.use('/graphql', bodyParser.json(), graphqlExpress({ schema }));
server.use('/graphiql', graphiqlExpress({
  endpointURL: '/graphql',
  subscriptionsEndpoint: 'ws://localhost:3000/subscriptions',
}));

// We wrap the express server so that we can attach the WebSocket for subscriptions
const ws = createServer(server);
ws.listen(PORT, () => {
  console.log('GraphQL Server is running');
  // Set up the WebSocket for handling GraphQL subscriptions
  new SubscriptionServer({
    execute,
    subscribe,
    schema
  }, {
    server: ws,
    path: '/subscriptions',
  });
});
Run Code Online (Sandbox Code Playgroud)

我正在使用 react-apollo: 1.4.10, apollo-client: 1.9.0-0

小智 6

基本上,您必须用您机器的 IP 地址替换 localhost。该问题已在此处重新报告, https://github.com/apollographql/apollo-client/issues/1757

要检查您的 IP 地址,请参阅此视频https://www.youtube.com/watch?v=TRFtQzx0Y0M


小智 5

我遇到了同样的问题,我在这里找到了解决方案https://github.com/apollographql/apollo-client/issues/1757

基本上,您需要在 createNetworkInterface 函数中使用计算机的 IP 地址,因此请更改此设置:

const networkInterface = createNetworkInterface({ uri: 'http://localhost:3000/graphql' });
Run Code Online (Sandbox Code Playgroud)

对此:

const networkInterface = createNetworkInterface({ uri: 'http://YOURIPADDRESS:3000/graphql' });
Run Code Online (Sandbox Code Playgroud)