gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 21:32:19 25 4
gpt4 key购买 nike

我基本上创建了快速服务器,然后添加了 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 链接会非常有帮助:)

非常感谢

最佳答案

我有一个 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
})
})

这个想法是:你创建一个 webSockerServer(来自'http')并作为参数发送到快速服务器中。

关于express - 如何解决 GraphQL 订阅服务器中的 webSocket 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47873942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com