Docs: Apollo Server example throws error
Description
When trying run Apollo Server code example from https://graphql.org/code/ I got an error:
throw new Error('You must `await server.start()` before calling `server.' +
^
Error: You must `await server.start()` before calling `server.applyMiddleware()`
Steps to Reproduce
npm install apollo-server-express expressrun node server.jswith this code inserver.js:
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const typeDefs = gql`
type Query {
hello: String
}
`;
const resolvers = {
Query: {
hello: () => 'Hello world!',
},
};
const server = new ApolloServer({ typeDefs, resolvers });
const app = express();
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
console.log('Now browse to http://localhost:4000' + server.graphqlPath)
);
Expected Result
code runs with no errors
Actual Result
code runs with error
server.start() is a promise so you need to resolve it. Checkout apollo docs on how to use it https://github.com/apollographql/apollo-server/tree/main/packages/apollo-server-express#express
Hey it is pretty simple to solve this issue. Here is what I did
const express = require("express");
const { ApolloServer, gql } = require("apollo-server-express");
const typeDefs = gql`
type Query {
hello: String
}
`;
const resolvers = {
Query: {
hello: () => "Hello world!",
},
};
const server = new ApolloServer({ typeDefs, resolvers });
const main = async () => {
const app = express();
await server.start();
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
console.log("Now browse to http://localhost:4000" + server.graphqlPath)
);
};
main();
Basically create a main function and make it an async function and await server.start();
Hey it is pretty simple to solve this issue. Here is what I did
const express = require("express"); const { ApolloServer, gql } = require("apollo-server-express"); const typeDefs = gql` type Query { hello: String } `; const resolvers = { Query: { hello: () => "Hello world!", }, }; const server = new ApolloServer({ typeDefs, resolvers }); const main = async () => { const app = express(); await server.start(); server.applyMiddleware({ app }); app.listen({ port: 4000 }, () => console.log("Now browse to http://localhost:4000" + server.graphqlPath) ); }; main();Basically create a main function and make it an async function and await
server.start();
Thank you but I know how to solve it. I am just pointing that there is an error in the docs
I will open pr and fix this issue.
As discussed in https://github.com/graphql/graphql.github.io/pull/1082 this was fixed, but the new instructions are not entirely accurate now that Apollo Server 4 has shipped. We'll get this updated - thanks!
@hwillson is this still the case?