需要先下载apollo-server-express,apollo-server-express是Express框架下,用于构建GraphQL服务的中间件,属于Apollo Server的一部分:
npm install apollo-server-express
随后在index.js添加 apollo-server-express包:
const {ApolloServer, gql} = require('apollo-server-express');
完整版index.js 文件:
原版 server.graphqlPath
在 Apollo Server 3 中被弃用,在 console.log
语句中直接使用中间件路径 /api并增加await server.start()函数。
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const port = process.env.PORT || 8080;
const typeDefs = gql`
type Query {
hello: String
}
`;
const resolvers = {
Query: {
hello: () => 'Hello world!',
},
};
const app = express();
(async () => {
const server = new ApolloServer({
typeDefs,
resolvers,
});
// 等待 Apollo Server 启动
await server.start();
server.applyMiddleware({ app, path: '/api' });
app.listen({ port }, () => {
console.log(`GraphQL server is running at http://localhost:${port}/api`);
});
})();
在浏览器输入http://localhost:8080/api,打开后如下: