I’ve been getting this error when I run npx diagnose-endpoint for my apollo client.
**Diagnosing https://localhost:3000/api/graphql
⚠️ Introspection query could not parse "POST body missing, invalid Content-Type, or JSON object has no keys." As valid json. Here is the error: SyntaxError: Unexpected token "P", "POST body "… is not valid JSON **
I’m setting up GraphQL as a next.js API endpoint. I’m pretty sure my schema and resolver have no errors.
This is my next.js api endpoint:
import { server } from "../../graphql/apollo";
import { NextApiRequest, NextApiResponse } from "next";
import Cors from "cors";
// Initializing the cors middleware
// You can read here: https://github.com/expressjs/cors#configuration-options
const cors = Cors({
methods: ["POST"],
});
// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
function runMiddleware(
req: NextApiRequest,
res: NextApiResponse,
fn: Function
) {
return new Promise((resolve, reject) => {
fn(req, res, (result: any) => {
if (result instanceof Error) {
return reject(result);
}
return resolve(result);
});
});
}
export const config = {
api: {
bodyParser: false,
},
};
const startServer = server.start();
export default async function handler(
req: NextApiReque`st,
res: NextApiResponse
) {
res.setHeader("Content-Type", "application/json");
// Run cors middleware (to allow Apollo Studio access)
await runMiddleware(req, res, cors);
// run apollo server
await startServer;
await server.createHandler({ path: "/api/graphql" })(req, res);
}
I tried implementing
- "micro-cors" and wrapped it around
export default async function handler(
- Adding middleware function
- No CORS with just setting headers as res.setHeader("…")
None of them worked.