admin 管理员组

文章数量: 1086019

I'm working on a mobile app with a react native frontend using graphql and expo, and have created a development build for it. The node.js server is running on an AWS EC2 that currently allows inbound and outbound traffic from all ports (I wasn't sure if port access was the issue). When I test the development build's connection to the server when run locally on my ip, I have no issues connecting, but I can't seem to get it to connect to my server on the EC2. The server is running and when I've tested curl :4000/graphql -H "Content-Type: application/json" -d '{"query": "{ __typename }"}' in my desktop's terminal I get the correct response. In the app though, when I've tested

fetch(':4000/graphql', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ query: '{ __typename }' }),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

I get Error: [TypeError: Network request failed]. I also can't sign into a user account because I can't access my backend from the app, and I keep getting:

{
  "name": "ApolloError",
  "graphQLErrors": [],
  "protocolErrors": [],
  "clientErrors": [],
  "networkError": {},
  "message": "Network request failed",
  "cause": {}
}

whenever I try to. I've never tried running a server anywhere, but locally, so I'm not sure if I'm doing something wrong, but I keep trying all of the suggestions Amazon Q is giving me to test and fix my connection, but none of them have worked so far. I would really appreciate any help or advice on how I could get this to work. Thank you!

client.ts

import { ApolloClient, split, createHttpLink, HttpLink, InMemoryCache, from } from '@apollo/client';
import { getMainDefinition } from '@apollo/client/utilities';
import { setContext } from "@apollo/client/link/context";
import AsyncStorage from '@react-native-async-storage/async-storage';
import { GraphQLWsLink } from "@apollo/client/link/subscriptions";
import { createClient } from "graphql-ws";
import { onError } from "@apollo/client/link/error";
import "react-native-devsettings";
import { loadErrorMessages, loadDevMessages } from "@apollo/client/dev";


if (__DEV__) {
  // Adds messages only in a dev environment
  loadDevMessages();
  loadErrorMessages();
}

const wslink = new GraphQLWsLink(
  createClient({
    url: ":4000/graphql"
  }),
);



const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.forEach(({ message, locations, path }) =>
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
      )
    );
  if (networkError) console.log(`[Network error]: ${networkError}`);
});

const httpLink = new HttpLink({
  uri:":4000/graphql"
});


const authLink = setContext(async (_, { headers }) => {
  const token = await AsyncStorage.getItem('token');
  try {
  if (token !== null) {
  return {
    headers: {
      ...headers,
      authorization: `Bearer ${token}` || null,
    }
   }
  }
}
catch (error) {
  throw error;
}
});

const splitLink = split(
  ({ query }) => {
    const definition = getMainDefinition(query);
    return (
      definition.kind === 'OperationDefinition' &&
      definition.operation === 'subscription'
    );
  },
  wslink,
  authLink.concat(httpLink)
);



export const client = new ApolloClient({
  link: from([errorLink, splitLink]),
  cache: new InMemoryCache(),
  connectToDevTools: true,
});

  const serializedState = client.cache.extract();

本文标签: amazon ec2Expo dev build on mobile phone won39t connect to server on AWS EC2Stack Overflow