最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何在 nodeJS + express 中设置 ApolloServer 4

网站源码admin32浏览0评论

如何在 nodeJS + express 中设置 ApolloServer 4

如何在 nodeJS + express 中设置 ApolloServer 4

我最近从 Apollo Server 3 升级到 Apollo Server 4。 使用此 文档 我编写了以下代码以在 express 中设置 Apollo Server 并在 localhost:3000/graphql 到达 graphQL 实验室但是在

await apolloServer.start()
之后,
app.use('/graphql',cors(),bodyParser.json(), expressMiddleware(apolloServer));
不起作用并且它为 localhost:3000/ 响应 404 错误graphql 路由,但其他一切正常。

我使用的包版本:

  • @apollo/server": "^4.7.0
  • 阿波罗服务器核心”:“^3.12.0
  • 正文解析器”:“^1.20.2
  • cors": "^2.8.5
  • 快递”:“^4.18.2

在 app.js 中

const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');

const http = require('http');
const {ApolloServer} = require('@apollo/server');

const { expressMiddleware } = require('@apollo/server/express4');
const { ApolloServerPluginDrainHttpServer } = require('@apollo/server/plugin/drainHttpServer');
const { ApolloServerPluginLandingPageDisabled } = require('@apollo/server/plugin/disabled');
const { ApolloServerPluginLandingPageGraphQLPlayground } = require('apollo-server-core');
const { startStandaloneServer} = require('@apollo/server/standalone');

const {typeDefs,resolvers} = require('./http/graphql');

class Application{

    host;
    constructor(){
        this.setupExpress();
    }


async setupExpress(){
let httpServer = http.createServer(app);
let apolloServer = new ApolloServer(
            {
                typeDefs,
                resolvers ,
                nodeEnv:'development',
                plugins : [
                    ApolloServerPluginDrainHttpServer({httpServer: httpServer}),    
                    ApolloServerPluginLandingPageGraphQLPlayground({}),
                    ApolloServerPluginLandingPageDisabled(),
                ]
            });

app.use('/gql',(req,res,next)=> res.json('gql'));

await apolloServer.start();
        
app.use('/graphql',cors(),bodyParser.json(), expressMiddleware(apolloServer));

let server = httpServer.listen(port,()=>{
            console.log(`Server is running on port ${port}`);
            this.host = server.address().address;
        })

            
        server.on('error',this.onError);
        server.on('listening',this.onListening);
}

在/http/graphql/index.js

const typeDefs = `#graphql
type Query {
    hello: String
}`;


const resolvers = {
    Query: {
        hello: ()=> 'world'
    }
};


module.exports = {
    typeDefs, resolvers
}

我使用 startStandaloneServer 而不是

await apolloServer.start();
,graphql lab 可以在 localhost:4001 中访问,但我想在 express 中集成 geaphql。

await startStandaloneServer(apolloServer,{
            context: async ({ req }) => ({ token: req.headers.token }),
            listen: { port: 4001},
          })
回答如下:
发布评论

评论列表(0)

  1. 暂无评论