Apollo Server v4 throws Cors issue

I am getting the typical CORS issue while accessing my backend

Here is my backend code

const app = express();
const httpServer = http.createServer(app);
const server = new ApolloServer({
  typeDefs,
  resolvers,
  plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
});

await server.start();

app.use(
  "/graphql",
  cors({
    origin: "http://localhost:3000/",
    credentials: true,
  }),
  express.json(),
  expressMiddleware(server)
);

await new Promise((resolve) => httpServer.listen({ port: 4000 }, resolve));

console.log("Server started at ", 4000);

Here is my frontend code

First way:

const client = new ApolloClient({
    cache: new InMemoryCache(),
  
    link: new HttpLink({
      uri: "https:/localhost:4000/graphql",
      
    }),
  });

Second way

const client = new ApolloClient({
    uri: "https:/localhost:4000/graphql",
    cache: new InMemoryCache(),
  });

Tried both way but still the issue persists

1 Like

@Pritish_Sawant
There is an issue in your backend code.

as is:

app.use(
  "/graphql",
  cors({
    origin: "http://localhost:3000/",
    credentials: true,
  }),
  express.json(),
  expressMiddleware(server)
);

to be:

app.use(
  "/graphql",
  cors({
    origin: "http://localhost:3000",   ///// you need to remove '/'
    credentials: true,
  }),
  express.json(),
  expressMiddleware(server)
);