I'm learning GraphQL and trying to set up Apollo Server with Express (v4), but I keep getting the following error when making a request to /graphql
:
req.body is not set; this probably means you forgot to set up the `json` middleware before the Apollo Server middleware.
Here's my server code:
const express = require("express");
const { ApolloServer } = require('@apollo/server');
const { expressMiddleware } = require('@apollo/server/express4')
const cors = require('cors');
async function startServer() {
const app = express();
const server = new ApolloServer({
typeDefs: `
type Todo {
id: ID!
title: String!
completed: Boolean!
}
type Query {
getTodos: [Todo]
}
`,
resolvers: {
Query: {
getTodos: () => []
}
}
});
await server.start();
app.use('/graphql', cors(), express.json(), expressMiddleware(server));
const PORT = process.env.PORT || 8000;
await new Promise((resolve) => app.listen(PORT, resolve));
console.log(`Server is running on port ${PORT}`);
}
startServer().catch((err) => {
console.error('Error starting the server:', err);
});
I've added express.json() before the expressMiddleware, but the error persists. Is there something I'm missing when using Apollo Server with Express 4 middleware?
Any help is appreciated!
if you are trying to open this http://localhost:8000/graphql in browser tab then it'll show that warning instead use postman or any other api tester and hit a post req at http://localhost:8000/graphql using some queries then it'll work.
cauz browser page is sending get req instead post and without Content-Type: application/json that's why it is giving this error (req.body
is not set; this probably means you forgot to set up the json
middleware before the Apollo Server
middleware.)