title: How to upload images to fastify + graphql backend with axios?
body: <p>When sending images via axios I found I have to use formdata. I add my images here but when sending the formdata my entire backend just freezes, just says "pending".</p>
  
  <p>Ive been following <a href="https://stackoverflow.com/questions/59043021/how-do-i-upload-files-to-a-graphql-backend-implemented-using-graphql-upload-usin">this</a></p>
  
  <p>And my attempt so far: </p>
  
  <p>backend: </p>
  
  <p>Apollo: </p>
  
  <pre><code>import { ApolloServer, makeExecutableSchema } from 'apollo-server-fastify';
  
  const schema = makeExecutableSchema({ typeDefs, resolvers });
  
  const apolloServer = new ApolloServer({
    schema,
    uploads: {
      maxFileSize: 10000000,
      maxFiles: 5,
    },
  });
  
  (async function() {
    app.register(apolloServer.createHandler({ path: '/api' }));
  })();
  </code></pre>
  
  <p>schema: </p>
  
  <pre><code>  scalar DateTime
    scalar Upload
  
    input addUser {
      Email: String!
      Password: String
      FirstName: String!
      LastName: String!
      Age: DateTime!
      JobTitle: String!
      File: Upload
    }
  
    type Mutation {
      register(input: addUser!): Boolean
    }
  </code></pre>
  
  <p>resolver: </p>
  
  <pre><code>  Mutation: {
      register: async (obj, args, context, info) =&gt; {
          // how to get the formData?
        },
    }
  </code></pre>
  
  <p>FrontEnd: </p>
  
  <p>I build the request like this: </p>
  
  <pre><code>const getMutation = (mutate: MutationNames, returParams?: any): any =&gt; {
    const mutation = {
      login: print(
        gql`
          mutation($email: String!, $password: String!) {
            login(email: $email, password: $password) {
              token
              refreshToken
            }
          }
        `
      ),
      register: print(
        gql`
          mutation(
            $firstName: String!
            $email: String!
            $lastName: String!
            $age: DateTime!
            $jobTitle: String!
            $file: Upload
          ) {
            register(
              input: {
                FirstName: $firstName
                LastName: $lastName
                Email: $email
                Age: $age
                JobTitle: $jobTitle
                File: $file
              }
            )
          }
        `
      ),
  
    }[mutate];
  
    if (!mutation) return {};
  
    return mutation;
  };
  </code></pre>
  
  <p>In this case im using the register mutation. </p>
  
  <p>I have a few hooks on how I handle the data fetching so Im not going to include it since it is alot of code. The data is fetched correctly in the front end and before posting to the backend im putting everything to a formData object: </p>
  
  <pre><code>  const submitForm: SubmitForm = (obj: SendObject) =&gt; {
      const Fdata = new FormData();
  
      Fdata.append('0', fileImp.file);
  
      Fdata.append('operations', JSON.stringify(obj.data));
  
      const map = {
        '0': ['variables.file'],
      };
      Fdata.append('map', JSON.stringify(map));
  
      callAxiosFn(
        {
          method,
          url: 'http://localhost:4000/api',
          data: Fdata,
          // headers: obj.headers,
        },
        qlType.toString()
      );
    };
  </code></pre>
  
  <p>gets called like this: </p>
  
  <pre><code>  const response = await axios({
      headers: {
        Accept: 'application/json',
        'x-token': localStorage.getItem('token'),
        'x-refresh-token': localStorage.getItem('refreshToken'),
        ...(config.headers || {}),
      },
      ...config,
    });
  </code></pre>
  
  <p>config is <code>AxiosRequestConfig</code></p>
  
  <p>What Im sending: </p>
  
  <p><a href="https://i.stack.imgur.com/qHUNk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qHUNk.jpg" alt="enter image description here"></a></p>
  
  <p>I dont exactly understand How the formdata will hit my resolver endpoint  and for that reason im doing something wrong since the backend returns: </p>
  
  <blockquote>
    <p>(node:748) UnhandledPromiseRejectionWarning: [object Array] (node:748)
    UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
    error originated either by throwing inside of an async function
    without a catch block, or by rejecting a promise which was not handled
    with .catch(). (rejection id: 1) (node:748) [DEP0018]
    DeprecationWarning: Unhandled promise rejections are deprecated. In
    the future, promise rejections that are not handled will terminate the
    Node.js process with a non-zero exit code.</p>
  </blockquote>
  
  <p>I realize this is alot but Im at the end of my vits here, been at this the entire day. Any help is deeply appreciated. </p>
  
  <p>EDIT: </p>
  
  <p>Since my backend was questioned I thought I would just show that when sending data without appending Formdata like I do above then I get it working: </p>
  
  <pre><code>  const submitForm: SubmitForm = (obj: SendObject) =&gt; {
  
      callAxiosFn(
        {
          method,
          url: 'http://localhost:4000/api',
          data: obj.data,
        },
        qlType.toString()
      );
    };
  </code></pre>
  
  <p>obj.data is: </p>
  
  <pre><code>{query: "mutation ($firstName: String!, $email: String!, $l… Age: $age, JobTitle: $jobTitle, File: $file})↵}↵", variables: {…}}
  query: "mutation ($firstName: String!, $email: String!, $lastName: String!, $age: DateTime!, $jobTitle: String!, $file: Upload) {↵  register(input: {FirstName: $firstName, LastName: $lastName, Email: $email, Age: $age, JobTitle: $jobTitle, File: $file})↵}↵"
  variables:
  age: "1977-04-04"
  email: "JhoneDoe@hotmail.com"
  file: File {name: "something.jpg", lastModified: 1589557760497, lastModifiedDate: Fri May 15 2020 17:49:20 GMT+0200 (centraleuropeisk sommartid), webkitRelativePath: "", size: 32355, …}
  firstName: "Jhon"
  jobTitle: "SomethingCool"
  lastName: "Doe"
  password: "CoolPassword!"123"
  __proto__: Object
  __proto__: Object
  </code></pre>
  
  <p>query getting sent in the browser: </p>
  
  <p><a href="https://i.stack.imgur.com/3KwLy.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3KwLy.jpg" alt="enter image description here"></a></p>
  
  <p>Backend reciving the data but the image is not included:
  <a href="https://i.stack.imgur.com/VJbcc.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VJbcc.jpg" alt="enter image description here"></a></p>
  
  <p>EDIT: </p>
  
  <p>Recently found that my fastify backend might have issues with reading formData.
  tried installing  </p>
  
  <pre><code>fastify-multipart
  </code></pre>
  
  <p>but got errors when registering it: </p>
  
  <blockquote>
    <p>FST_ERR_CTP_ALREADY_PRESENT(contentType) ^ FastifyError
    [FST_ERR_CTP_ALREADY_PRESENT]:</p>
  </blockquote>
  
  <p>After that I tried: </p>
  
  <pre><code>npm uninstall fastify-file-upload
  </code></pre>
  
  <p>Error remained. </p>