ChrisWill303
ChrisWill303

Reputation: 29

Graphql error, POST http://localhost:3000/graphql 400 (Bad Request)

I'm trying to find the error in my code to see why I am getting this error for the createHTTP link. This works in graphql just fine, but not on the application when the user goes to save a selection. Can anyone tell me where I went wrong? I apologize in advance for all the code, I want to make sure I get everything that might be relevant. I've been combing through it for a while now. To user information is saving to the database, the books are not. Thanks!!

import {
  ApolloClient,
  InMemoryCache,
  ApolloProvider,
  createHttpLink,
} from "@apollo/client";
import { setContext } from "@apollo/client/link/context";
import SearchBooks from "./pages/SearchBooks";
import SavedBooks from "./pages/SavedBooks";
import Navbar from "./components/Navbar";

const httpLink = createHttpLink({
  uri: "/graphql",
});

const authLink = setContext((_, { headers }) => {
  const token = localStorage.getItem("id_token");
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    },
  };
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
});

Mutations

import { gql } from "@apollo/client";

export const LOGIN_USER = gql`
  mutation login($email: String!, $password: String!) {
    login(email: $email, password: $password) {
      token
      user {
        _id
        username
      }
    }
  }
`;

export const ADD_USER = gql`
  mutation addUser($username: String!, $email: String!, $password: String!) {
    addUser(username: $username, email: $email, password: $password) {
      token
      user {
        _id
        username
        email
      }
    }
  }
`;

export const SAVE_BOOK = gql`
  mutation saveBook($input: SaveBookInput) {
    saveBook(input: $input) {
      username
      _id
      bookCount
      savedBooks {
        bookId
        authors
        title
        image
        link
        description
      }
    }
  }
`;

Query

import { gql } from "@apollo/client";

export const GET_ME = gql`
  {
    me {
      _id
      username
      email
      bookCount
      savedBooks {
        title
        bookId
        authors
        description
        image
        link
      }
    }
  }
`;

Upvotes: 0

Views: 1731

Answers (1)

Michel Floyd
Michel Floyd

Reputation: 20227

A 400 error is most often caused by syntax errors in your gql. Unfortunately it's kind of an opaque error message but I've run into it many times.

In this case you have:

export const GET_ME = gql`
  {
    me {
      _id
      username
    etc...
    }
  }
`

which is not an executable query.

I'd expect something more like:

export const GET_ME = gql`
  query getMe {
    me {
      _id
      username
      etc...
    }
  }
`

Assuming that in your typeDefs you have something like:

type Query {
  me: User
  …other queries
}

Upvotes: 2

Related Questions