React front end not reaching graphQL resolver

22 views Asked by At

EDIT: As soon as I posted this, I saw virtually the same post with the same answer, because of course I did.

=========

I'm building a MERN application. Trying to set up initial basic GraphQL mutations for adding a user and logging in, but I am not hitting the resolver at all. When I do either of these mutations, in the browser I get an Apollo error status 404, and in the server log I don't get any feedback.

However, when I access the server using the Apollo sandbox, it DOES work as planned: the appropriate messages get logged on the server side, and the appropriate content is sent back to the sandbox.

Since the sandbox is working, and since I'm not getting any errors starting the server, I believe the problem is client-side. Further below I've included the relevant server code, but I don't think it's at issue.

This is from mutations.tsx:

export const ADD_USER = gql`
  mutation AddUser($userName: String!, $password: String!, $email: String) {
    addUser(userName: $userName, password: $password, email: $email) {
      id
      token
    }
  }
`;

And this is from the component:

import { useMutation } from "@apollo/client";
import { LOGIN, ADD_USER } from "../../utils/mutations";

... other imports ...

export function Login() {

  ...state setting and other things...

  const [login] = useMutation(LOGIN);
  const [addUser] = useMutation(ADD_USER);

  ...some non-relevant handlers...

  const handleSignupSubmit = async (e: React.MouseEvent<HTMLButtonElement>) => {
    // Handler for login submission
    e.preventDefault();
    if (!validateForm(signupForm)) return;

    try {
      const { data } = await addUser({
        variables: {
          userName: signupForm.username,
          password: signupForm.pwd,
          email: signupForm.email,
        },
      });

      auth.login(data.login.token);
      navigate("/");
    } catch (err) {
      console.log(err);
    }
  };

  ...similar handler for login form...

  ...return JSX component including:
  
    <button
      id="signup-submit"
      disabled={
        !(signupForm.username.length > 0 && signupForm.pwd.length >= 6)
      }
      onClick={handleSignupSubmit}
     >
       Sign up
     </button>

  ...rest of JSX component

};

My tests on the signupForm state are fine, the submit handler is getting the appropriate data to work with. But when I fill out the form and submit, I get this in the console:

Failed to load resource: the server responded with a status of 404 (Not Found)   http://localhost:3000.graphql

ApolloError: Response not successful: Received status code 404

I've stared at the mutation definition and compared it to the typeDef on the server, and compared them to working mutations on my other app...I don't see any problem. But that's why I'm coming to you!

============

I copied much of the basic server code from an existing working application of mine. I expect that the problem isn't here in the server file, since the sandbox does connect. But here it is, just in case.

In server.js:

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: authMiddleware,
  formatError: (formattedError, error) => {
    console.log(formattedError.message);
    if (formattedError.message.startsWith("Database Error: ")) {
      return { message: "Internal server error" };
    }

    // Otherwise return the formatted error.
    return formattedError;
  },
});

// Create a new instance of an Apollo server with the GraphQL schema
const startApolloServer = async () => {
  await server.start();
  server.applyMiddleware({ app });

  db.once("open", () => {
    app.listen(PORT, () => {
      console.log(`API server running on port ${PORT}!`);
      console.log(
        `Use GraphQL at http://localhost:${PORT}${server.graphqlPath}`
      );
    });
  });
};

// Call the async function to start the server
startApolloServer();

I get no errors starting the server, and I DO get the API server running on port 3001! and the Use GraphQL at http://localhost:3001/graphql messages.

This is from typeDefs:

  ...basic types...

  type Query {
    getUser(lookupname: String!): User
  }

  type Mutation {
    addUser(userName: String!, email: String, password: String!): Auth
    login(userName: String!, password: String!): Auth
  }
`;

Again, this all works fine in the sandbox, and I don't get any errors on the server indicating that it's off.

Now the relevant resolvers:

const resolvers = {
  Date: DateResolver,

  Query: {

     ... queries here

  },

  Mutation: {
    addUser: async (parent, args) => {
      const { userName, email, password } = args;
      console.log(
        `username ${userName}, email ${email}, password is ${password.length} characters long.`
      );
      return { id: "testID", token: "testToken" };
    },

...etc.

  }
}

You can see I'm not really doing anything yet, just a test to confirm connection and transfer of data both ways.

0

There are 0 answers