如何使用graphQL使我的http和订阅在客户端上工作?

时间:2019-07-07 19:48:36

标签: reactjs graphql react-apollo apollo-client apollo-server

我终于用阿波罗完成了我的后端。 现在我移到了前端。

我使它可以使用正常的http连接,并从服务器(聊天应用程序)中获取了一些消息。 现在,我还尝试将订阅链接连接到它(这本身很令人困惑,因为外面有一些示例,每个人的做法都有些不同,但都没有用)。

这是我的索引文件在前端反应上的样子:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import { ApolloClient } from "apollo-client";
import { ApolloProvider } from "react-apollo";
import { WebSocketLink } from "apollo-link-ws";
import { ApolloLink } from "apollo-link";
import { HttpLink } from "apollo-link-http";
import { InMemoryCache } from "apollo-cache-inmemory";
const wsLink = new WebSocketLink({
  uri: `ws://localhost:4000/graphql`,
  options: {
    reconnect: true
  }
});
// Create an http link:
const httpLink = new HttpLink({
  uri: "http://localhost:4000/graphql"
});
const link = ApolloLink.from([httpLink, wsLink]);
const client = new ApolloClient({
  link,
  cache: new InMemoryCache()
});
ReactDOM.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  document.getElementById("root")
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.

serviceWorker.unregister();

我还尝试了不同的方法,例如从apollo-link拆分,如下所示:

const link = split(
  // split based on operation type
  ({ query }) => {
    const definition = getMainDefinition(query);
    return (
      definition.kind === "OperationDefinition" &&
      definition.operation === "subscription"
    );
  },
  wsLink,
  httpLink
);

我还尝试了apollo-boost而不是apollo-client中的ApolloClient。

有人可以帮我吗,因为我无法正常工作。 错误消息始终为:

  

与'ws:// localhost:4000 / graphql'的WebSocket连接失败:连接建立错误:net :: ERR_CONNECTION_REFUSED

如果您想查看完整的代码:https://github.com/SelfDevTV/graphql-simple-chat

0 个答案:

没有答案