我使用以下模式为Apollo / GraphQL订阅设置websockets连接:
import express from 'express';
import {
graphqlExpress,
graphiqlExpress,
} from 'apollo-server-express';
import bodyParser from 'body-parser';
import cors from 'cors';
import { execute, subscribe } from 'graphql';
import { createServer } from 'http';
import { SubscriptionServer } from 'subscriptions-transport-ws';
import { schema } from './src/schema';
const PORT = 3000;
const server = express();
server.use('*', cors({ origin: `http://localhost:${PORT}` }));
server.use('/graphql', bodyParser.json(), graphqlExpress({
schema
}));
server.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql',
subscriptionsEndpoint: `ws://localhost:${PORT}/subscriptions`
}));
// Wrap the Express server
const ws = createServer(server);
ws.listen(PORT, () => {
console.log(`Apollo Server is now running on http://localhost:${PORT}`);
// Set up the WebSocket for handling GraphQL subscriptions
new SubscriptionServer({
execute,
subscribe,
schema
}, {
server: ws,
path: '/subscriptions',
});
});
如何更改连接以使用安全的websockets协议?简单地将'ws://'更改为'wss://'不起作用。
答案 0 :(得分:0)
我为graphql-subscription
Websocket安全连接制作了一个示例。
关键是您需要tls
或ssl
凭据。
对于开发,您可以使用openssl
生成自签名凭证。
答案 1 :(得分:-1)
您需要使用https
代替http
包。
您还需要有证书。收集自签名或来自证书颁发机构。
看起来像这样:
import { createServer } from 'https';
...
// load / get certificate
...
const wss = createServer(sslCredentails, server);
wss.listen(PORT, () => {
console.log(`Apollo Server is now running on https://localhost:${PORT}`);
// Set up the WebSocket for handling GraphQL subscriptions
new SubscriptionServer({
execute,
subscribe,
schema
}, {
server: wss,
path: '/subscriptions',
});
});