WebSocket与“ ws:// localhost:4444 / subscriptions”的连接失败:WebSocket在建立连接之前已关闭

时间:2019-12-14 15:34:22

标签: apollo apollo-client apollo-server

操作系统:Windows 10 Pro
快递:4.17.1
apollo-server-express:2.9.13
阿波罗客户端:2.6.4
阿波罗链接上下文:1.0.18
阿波罗链接-http:1.5.15
apollo-link-ws:1.0.18

因此,我正在从graphql-yoga迁移到apollo-server 2,并且遇到ws连接问题(见图)。我在俯视什么?

ws-error.jpg

我的代码如下:

withData.js

const endpoint = `http://localhost:4444/graphql`;
const endpointWS = `ws://localhost:4444/subscriptions`;

  const httpLink = createHttpLink({
    uri: process.env.NODE_ENV === 'development' ? endpoint : prodEndpoint,
    credentials: 'include',
  });

  const wsLink = process.browser ? new WebSocketLink({
    uri: process.env.NODE_ENV === 'development' ? endpointWS : prodEndpointWS,
    options: {
      reconnect: true,
      timeout: 3000,
    }
  }) : null;

  const authLink = setContext(() => {
    return {
      headers: {
        ...headers,
      }
    }
  });

const link = process.browser ? split(
   ({ query }) => {
    const definition = getMainDefinition(query);
    return (
      definition.kind === 'OperationDefinition' &&
      definition.operation === 'subscription'
    );
  },
  wsLink,
  httpLink,
) : httpLink;

index.js

const PORT = '4444';
const path2 = '/graphql';

const createServer = require('./createServer');
const server = createServer();
const app = express();

app.use(cookieParser());

server.applyMiddleware({
  app, 
  path: path2,
  cors: {
    credentials: true,
    origin: process.env.FRONTEND_URL,
  },
 });
const httpServer = http.createServer(app);
server.installSubscriptionHandlers(httpServer);

httpServer.listen(PORT, err => {
  if (err) throw err
  console.log(`? Server ready at http://localhost:${PORT}${server.graphqlPath}`)
  console.log(`? Subscriptions ready at ws://localhost:${PORT}${server.subscriptionsPath}`)
});

createServer.js

const Mutation = require('./resolvers/Mutation');
const Query = require('./resolvers/Query');
const Subscription = require('./resolvers/Subscription');
const db = require('./db');
const typeDefsFile = importSchema(__dirname.concat('/schema.graphql'));
const typeDefs = gql(typeDefsFile);

function createServer() {
    return new ApolloServer({
        typeDefs,
        resolvers: {
            Mutation,
            Query,
            Subscription,
        },
        cors: {
          credentials: true,
          origin: process.env.FRONTEND_URL,
        },
        subscriptions: {
          keepAlive: 1000,
          path: '/subscriptions',
        },
        playground: process.env.NODE_ENV === 'production' ? false : '/',
        tracing: true,
        introspection: true,
        context: req => ({ ...req, db }),
    });
}

module.exports = createServer;

db.js

const { Prisma } = require('prisma-binding');

const db = new Prisma({
    typeDefs: __dirname + "/schema_prep.graphql",
    endpoint: process.env.PRISMA_ENDPOINT,
    secret: process.env.PRISMA_SECRET,
    debug: false,
});

module.exports = db;

Subscriptions.js

const Subscription = {   
    item: {   
        subscribe: async (parent, args, ctx, info) => {   
            const itemResult = await ctx.db.subscription   
                .item({   
                    where: {   
                        mutation_in: ['CREATED', 'UPDATED'],   
                    },   
                },   
                info   
            );   
            return itemResult;   
        },   
    },   
    itemDeleted: {   
        subscribe: (parent, args, ctx, info) => {   
          const selectionSet = `{ previousValues { id, userIdentity } }`   
          return ctx.db.subscription.item(   
            {   
              where: {   
                mutation_in: ['DELETED'],   
              },   
            },   
            selectionSet,   
          );   
        },   
        resolve: (payload, args, context, info) => {   
          return payload ? payload.item.previousValues : payload   
        },   
    },   
};   

module.exports = Subscription;

1 个答案:

答案 0 :(得分:0)

我通过将查询和变异解析器中上下文的响应和请求属性分别从ctx.response和ctx.request更改为ctx.res和ctx.req来解决了这个问题。