Issue with file upload using Apollo Server and GraphQL

45 Views Asked by At

I am encountering an issue with file upload functionality in my Node.js backend application using Apollo Server and GraphQL. I am currently using Node.js version 18.19 and Apollo Server from '@apollo/server'. My goal is to allow file transmission between the frontend and backend.

However, when deploying to production, I receive the following error message:

{
    "errors": [
        {
            "message": "POST body missing, invalid Content-Type, or JSON object has no keys.",
            "extensions": {
                "code": "BAD_REQUEST"
            }
        }
    ]
}

I suspect that the problem lies within my index.ts file, where I have implemented Apollo Server and middleware for file upload using graphql-upload-ts. Here's a snippet of my index.ts:

import { ApolloServer } from '@apollo/server'
import { Modules } from './modules'
import { Context } from './types/Context'
import http from 'http'
import express from 'express'
import cors from 'cors'
import { graphqlUploadExpress } from 'graphql-upload-ts'

async function main() {
    // Other configurations and setup
    
    const app = express()
    const httpServer = http.createServer(app)

    // Create Apollo Server instance
    const server = new ApolloServer<Context>({
        // Apollo Server configurations
        plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
    })
    await server.start()

    // Middleware setup
    app.use(
    '/',
    cors<cors.CorsRequest>(),
    express.json(),
    expressMiddleware(server, {
        context: async ({ req }) => await getContext(req.headers, modules),
    }),
    )

    app.use(graphqlUploadExpress({ maxFileSize: SIZE_LIMIT, maxFieldSize: SIZE_LIMIT, maxFiles: 10 }))

    const url = await new Promise<void>((resolve) => httpServer.listen({ port: appPort }, resolve))
        .then(() => `http://localhost:${appPort}/`)
    console.info(` Server ready at port ${url}`)
}

main()

It seems that the middleware graphqlUploadExpress is not being applied correctly, causing the file upload functionality to fail. I am considering whether I should use the 'apollo-server-express' dependency instead of '@apollo/server'. Could this be the solution to my problem?

I am also open to any other suggestions or advice on how to properly implement file upload functionality in my backend application. Please note that many of the configurations in my index.ts file are necessary for other parts of the project to function correctly. Thank you for your assistance!

0

There are 0 best solutions below