出现"Apollo-Client with subscriptions: failed: WebSocket握手期间出错:响应代码意外:400"错误通常是由于Websocket握手失败引起的。以下是一些可能的解决方法:
检查服务器端的配置:首先确保服务器端正确地配置了Websocket协议和相关的订阅功能。确保服务器端的URL和端口正确,并且在服务器端启用了Websocket协议。
检查客户端的配置:确保在Apollo-Client中正确配置了Websocket链接。检查是否提供了正确的URL和端口,并且使用了正确的协议(通常是"ws://"或"wss://")。
检查网络连接:确保客户端能够正常连接到服务器。尝试在浏览器中访问Websocket端点,以确保网络连接正常。如果存在防火墙或代理服务器,请确保它们允许Websocket连接。
检查订阅查询:检查订阅查询是否正确地定义和发送到服务器。确保订阅查询的语法正确,并且订阅的事件能够正确地触发服务器端的订阅逻辑。
以下是一个使用Apollo-Client进行订阅的示例代码:
import { ApolloClient, InMemoryCache, createHttpLink, split } from '@apollo/client';
import { getMainDefinition } from '@apollo/client/utilities';
import { WebSocketLink } from '@apollo/client/link/ws';
const httpLink = createHttpLink({
uri: 'http://localhost:4000/graphql',
});
const wsLink = new WebSocketLink({
uri: 'ws://localhost:4000/graphql',
options: {
reconnect: true,
},
});
const link = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
httpLink
);
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
});
// 订阅示例
const subscription = gql`
subscription {
newMessage {
id
content
}
}
`;
const observer = client.subscribe({ query: subscription });
observer.subscribe({
next: (response) => {
console.log(response);
},
error: (error) => {
console.error(error);
},
});
请确保替换示例代码中的URL和端口为正确的服务器端配置。如果问题仍然存在,请检查服务器端和客户端的日志以获取更多详细信息,并尝试根据错误消息进一步调查和解决问题。