调用socket.send()后出现iterator.next is not a function错误求助
问题
执行socket.send()发送消息时收到错误:
Received message: {"type":"error","id":15,"payload":{"name":"TypeError","message":"iterator.next is not a function"}}
触发错误的代码:
socket.send(JSON.stringify(message))
完整代码如下:
export default function () { const url = "wss://test.com/graphql"; const query = `test ($scope: String = "DEFAULT", $test: Boolean = false) { update(scope: $scope: $test) { id status __typename } __typename } } `; const variables = { scope: "DEFAULT", topic: [ "football.*.6ec99981-9ffe-4722", ], }; const params = { headers: { Authorization: "testauth", "Sec-WebSocket-Protocol": "graphql-ws", Pragma: "no-cache", }, }; const message = { id: 15, payload: { query, variables }, }; const response = ws.connect(url, params, function (socket) { socket.on("open", function open() { console.log("WebSocket connection established."); // Send the GraphQL message socket.send(JSON.stringify(message)); }); }
原因分析
- GraphQL查询语法错误:查询中的
update(scope: $scope: $test)用冒号分隔参数,正确格式应为逗号,无效语法导致服务端解析器处理时抛出迭代器相关错误。 - 消息不符合graphql-ws协议规范:graphql-ws要求消息必须包含
type字段(比如start用于启动订阅),当前消息缺少该字段,服务端无法识别消息类型。 - 变量不匹配:查询定义了
$test变量,但variables对象中没有对应的test属性,参数缺失引发解析异常。
修复方案
- 修正查询语法:将参数分隔的冒号改为逗号,确保参数名与变量名对应:
test ($scope: String = "DEFAULT", $test: Boolean = false) { update(scope: $scope, test: $test) { id status __typename } __typename } - 完善消息格式:添加符合graphql-ws协议的
type字段:const message = { id: 15, type: "start", payload: { query, variables }, }; - 补全变量:在
variables中添加test字段匹配查询定义:const variables = { scope: "DEFAULT", test: false, topic: [ "football.*.6ec99981-9ffe-4722", ], };
修复后的完整代码示例
export default function () { const url = "wss://test.com/graphql"; const query = `test ($scope: String = "DEFAULT", $test: Boolean = false) { update(scope: $scope, test: $test) { id status __typename } __typename }`; const variables = { scope: "DEFAULT", test: false, topic: [ "football.*.6ec99981-9ffe-4722", ], }; const params = { headers: { Authorization: "testauth", "Sec-WebSocket-Protocol": "graphql-ws", Pragma: "no-cache", }, }; const message = { id: 15, type: "start", payload: { query, variables }, }; const response = ws.connect(url, params, function (socket) { socket.on("open", function open() { console.log("WebSocket connection established."); socket.send(JSON.stringify(message)); }); }); }
内容的提问来源于stack exchange,提问作者BruceyBandit
相关产品推荐
相关产品推荐

