GraphQL: POST body missing, invalid Content-Type, or JSON object has no keys
Asked Answered
H

2

8

I am trying to create a mutation but I keep getting a POST body is missing. I can log the data before urql and codegen hooks are called and I can see the data in the variables on the error, but chrome keeps imploding with a "POST body missing" error and the server's resolver is never hit.

I am using Urql with Codegen on a React Client and using Apollo-server on an Express API.

Here is my code:

Mutation Definition (for codegen)

mutation UserLogin($email: String!, $password: String!) {
  login(email: $email, password: $password) {
    errors {
      email {
        error
        isValid
      }
      password {
        error
        isValid
      }
    }
    token
  }
}

codegen outputs:

export const UserLoginDocument = gql`
    mutation UserLogin($email: String!, $password: String!) {
  login(email: $email, password: $password) {
    errors {
      email {
        isValid
        error
      }
      password {
        isValid
        error
      }
    }
    token
  }
}
    `;

export function useUserLoginMutation() {
  return Urql.useMutation<UserLoginMutation, UserLoginMutationVariables>(UserLoginDocument);
};

Using this hook fails, so I tried using urql directly: useMutation Hook (same error)

  const [, executeMutation] = useMutation(`
      mutation($email: String!, $password: String!) {
        login(email: $email, password: $password) {
          errors {
            email {
              error
              isValid
            }
            password {
              error
              isValid
            }
          }
          token
        }
      }
  `);

I have confirmed that I can execute the query with a raw fetch:

async function fetchGraphQL(text: any, variables: any, token: string = '') {
  const response = await fetch('http://localhost:4000/graphql', {
    method: 'POST',
    headers: {
      Authorization: `bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      query: text,
      variables,
    }),
  });
  return await response.json();
}

However, attempts to generate a hook via codegen or just using urql's useMutation hook are resulting in:

{
...
  "source": {
  "body": "mutation ($email: String! $password: String!) { login(email: $email password: $password) { errors { email { error isValid } password { error isValid } } token } }",
...
        },
        "variables": {
            "email": "...",
            "password": "..."
        },
        "kind": "mutation",
        "context": {
            "url": "http://localhost:4000/graphql",
            "preferGetMethod": false,
            "suspense": false,
            "requestPolicy": "cache-first",
            "meta": {
                "cacheOutcome": "miss"
            }
        }
    },
    "error": {
        "name": "CombinedError",
        "message": "[Network] Bad Request",
        "graphQLErrors": [],
        "networkError": {},
        "response": {}
    }
}

I have another, very simple mutation that works fine:

mutation SetActiveChild($childId: String!) {
  setActiveChild(childId: $childId) 
}

Here are my typeDefs and resolvers:

typeDefs

export const typeDefs = gql`
  ...
  type Mutation {
    "user login"
    login(email: String!, password: String!): LoginResponse
  }
  ...
`

resolvers

export const resolvers = {
  Query: {
    ...
  },
  Mutation: {
    login: ({}, user: UserRegister) => {
      return AuthGraph.login(user);
    },
    ...
  },
};

I'm pretty new to GraphQL, many thanks in advance to help me understand what I've done wrong.

Hebel answered 23/9, 2021 at 19:32 Comment(2)
did you find the answer to this? im facing the exact same issue :(Afroasian
I was unable to find an answer and ended up switching to ApolloHebel
Y
12

Add following thing to apolloServer configuration

// This middleware should be added before calling `applyMiddleware`.
  app.use(graphqlUploadExpress());

Reference: https://www.apollographql.com/docs/apollo-server/data/file-uploads/

Yearning answered 17/10, 2021 at 17:51 Comment(3)
Thank you for the response. I'm confused how this helps though because I'm not uploading a file.Hebel
What if I'm getting the same error but I'm not using express, only Apollo?Elyssa
This is not the correct answer if you are not uploading a file.Dracaena
D
8

I ran into this issue and turned out that in my request Header my Content-Type was being set as text/html; charset=utf-8 Once I changed that to application/json The problem got solved

Dracaena answered 20/4, 2022 at 22:48 Comment(1)
Thank you! This fixed it for me: ``` headers: { "Content-Type": "application/json", }, ```Shrewd

© 2022 - 2024 — McMap. All rights reserved.