我基本创建了快速服务器,然后添加了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’)并在快递服务器中作为param发送.