【发布时间】:2020-02-05 17:17:44
【问题描述】:
我在 Apollo GraphQL 订阅上使用 react,我可以在 Apollo Playground 上接收更新,但不能在客户端上接收更新。以下是 Apollo Playground 上的回复:
Graphql 服务器位于 http://localhost:4000/,订阅位于 ws://localhost:4000/graphql。但是,它可以在操场上工作,但不能在客户端上工作。我已经以这种方式设置了 Apollo 客户端来接收来自服务器的更新:
import ApolloClient from 'apollo-boost';
import { WebSocketLink } from 'apollo-link-ws';
import { HttpLink } from 'apollo-link-http';
import { split } from 'apollo-link';
import { getMainDefinition } from 'apollo-utilities';
const httpLink = new HttpLink({
uri: 'http://localhost:4000/graphql'
});
export const wsLink = new WebSocketLink({
uri: `ws://localhost:4000/graphql`,
options: {
reconnect: false
}
});
export const link = split(
// split based on operation type
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
httpLink,
);
export const client = new ApolloClient({
uri: 'http://localhost:4000/',
});
在我看来我用过useSubscriptions:
const MESSAGE_SENT_SUBSCRIPTION = gql`subscription {
messageSent {
id
message
}
}`
const {data: newMessage, loading: newMessageLoading} = useSubscription(MESSAGE_SENT_SUBSCRIPTION, {});
在渲染时,我使用过:
{!newMessageLoading && JSON.stringify(newMessage)}
但是从客户端,它没有收到更新,但我确信它与 Graphql WebSockets 服务器连接。
服务器端:
let database = require("./src/database.js")
let schema = require("./src/schema.js");
let resolvers = require("./src/resolvers.js");
let {ApolloServer} = require("apollo-server");
// The ApolloServer constructor requires two parameters: your schema
// definition and your set of resolvers.
const server = new ApolloServer({
typeDefs: schema,
resolvers: resolvers,
context: {
database
}
});
// The `listen` method launches a web server.
server.listen().then(({ url,subscriptionsUrl ,subscriptionsPath}) => {
console.log(`???? Server ready at ${url}`);
console.log(`realtime here at ${subscriptionsUrl} and path ${subscriptionsPath}`)
});
我在这里做错了什么,有没有人遇到过这样的问题?
【问题讨论】:
-
我更改了端口并收到错误
ws即WebSocket is closed before the connection is established. -
@DanielRearden 客户端在端口 3000 上,graphql 端口是 4000。
标签: reactjs graphql apollo apollo-client graphql-subscriptions