如何解决GraphQL订阅服务器中的webSocket错误

5

我基本上创建了一个Express服务器,然后添加了SubscriptionServer。

/*
*   GRAPHQL SERVER
*/

const graphqlServer = express()
graphqlServer.use(cors())
graphqlServer.use('/graphql', bodyParser.json(), graphqlExpress({ schema: schema }))
graphqlServer.get('/graphiql', graphiqlExpress({ endpointURL: '/graphql', subscriptionsEndpoint: `ws://localhost:${process.env.GRAPHQL_PORT}/subscriptions`, }))

graphqlServer.listen(process.env.GRAPHQL_PORT, () => {

  SubscriptionServer.create(
    {
      schema,
      execute,
      subscribe,
    },
    {
      server: graphqlServer,
      path: '/subscriptions',
    },
  )

  console.log(`
    - GraphQL server listening on http://localhost:${process.env.GRAPHQL_PORT}
    - GraphQL subscriptions listening on ws://localhost:${process.env.GRAPHQL_PORT}/subscriptions
    `)
})

当我尝试连接GraphQLi订阅服务器时,它抛出了一个错误。

WebSocket connection to 'ws://localhost:10005/subscriptions' failed: Connection closed before receiving a handshake response

我不知道这意味着什么,也不知道问题出在哪里。

如果有人做过类似的项目,可以给我发送GitHub链接,那将非常有帮助:)

非常感谢

1个回答

1
我有一个TypeScript示例,大致如下:
import * as express from 'express'
import * as cors from 'cors'
import * as bodyParser from 'body-parser'
import { graphiqlExpress, graphqlExpress } from 'apollo-server-express'
import { schema } from './schema'
import { createServer } from 'http'
import { SubscriptionServer } from 'subscriptions-transport-ws'
import { execute, subscribe } from 'graphql'

const server = express()

const PORT = Number(process.env.PORT) || 3000

const GRAPHQL_ROUTE = '/graphql'
const GRAPHIQL_ROUTE = '/graphiql'
const GRAPHQL_SUBSCRIPTIONS_ROUTE = '/subscriptions'

server.use(
    '*',
    cors({
        origin: `http://localhost:${PORT}`,
    })
)

server.use(
    GRAPHQL_ROUTE,
    bodyParser.json(),
    graphqlExpress({
        schema
    })
)

server.use(
    GRAPHIQL_ROUTE,
    graphiqlExpress({
        endpointURL: GRAPHQL_ROUTE,
        subscriptionsEndpoint: `ws://localhost:${PORT}${GRAPHQL_SUBSCRIPTIONS_ROUTE}`
    })
)

const webSocketServer = createServer(server)

webSocketServer.listen(PORT, () => {
    console.log(`GraphQL api on http://localhost:${PORT}${GRAPHQL_ROUTE}`)
    console.log(`GraphiQL interface on http://localhost:${PORT}${GRAPHIQL_ROUTE}`)
    console.log(`WebSocket Server on ws://localhost:${PORT}${GRAPHQL_SUBSCRIPTIONS_ROUTE}`)

    new SubscriptionServer({
        execute,
        subscribe,
        schema
    }, {
        server: webSocketServer,
        path: GRAPHQL_SUBSCRIPTIONS_ROUTE
    })
})

这个想法是:您创建一个WebSocket服务器(从“http”),并将其作为参数发送到Express服务器中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接