FetchError: invalid json response body GraphQL

FetchError: invalid json response body GraphQL


0

I’m using @apollo/datasource-rest to wrap a 3rd party API. The endpoint I’m trying to hit checks if an email is already in use or not. If the email is in use the response looks like this

    "body": "True",
    "statusCode": 200,
    "contentType": "application/json",

If the email is not in use the api returns a 404 like this

    "body": "",
    "statusCode": 404,
    "statusDescription": "Resource not found",

The problem is the express.json() or bodyParser.json() middleware throws an error because "True" is not valid JSON and it is only getting parsed as json because the 3rd party API is sending back a response header of "Content-Type": "application/json".

Is there a way to change the content type of the response before it hits the express.json() or bodyParser.json() middleware

Here is my Apollo Express Server

const main = async () => {
  const app = express()
  const httpServer = http.createServer(app)
  const port = process.env.PORT

  const schema = makeExecutableSchema({ resolvers, typeDefs })

  // Set up Apollo Server
  const server = new ApolloServer<MyContext>({
    schema,
    plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
  })

  await server.start()

  app.use(
    '/graphql',
    cors<cors.CorsRequest>({
      origin: '*',
    }),
    json(),
    expressMiddleware(server, {
      context: async ({ req, res }) => {
        return {
          req,
          res,
          datasources: {
            someAPI: new SomeAPI(),
          },
        }
      },
    }),
  )

  await new Promise<void>((resolve) => httpServer.listen({ port }, resolve))
  console.log(`🚀 Server ready at https://localhost:${port}/graphql`)
}

main().catch((error) => {
  console.error(error)
})


Load 7 more related questions


Show fewer related questions

0



Leave a Reply

Your email address will not be published. Required fields are marked *