如何解决这个错误,我用 AWS IoT 运行我的 Node.js 然后它有时会显示这个错误:
throw er; // Unhandled 'error' event
^
Error: How (/home/ec2-user/work/nodejs_27_01/node_modules/end-of-stream/index.js:54: 86)
at processTicksAndRejections (internal/process/task_queues.js:79:11)
Emitted 'error' event on DeviceClient instance at:
at MqttClient.<anonymous> (/home/ec2-user/work/nodejs_27_01/node_modules/aws-iot-device-sdk/ device/index.js:772:15)
at MqttClient.emit (events.js:333:22)
at MqttClient.EventEmitter.emit (domain.js:485:12)
at TLSSocket.f (/home/ec2-user/work/nodejs_27_01/node_modules/once/once.js:25:25)
at onclosenexttick (/home/ec2-user/work/nodejs_27_01/node_modules/end-of-stream/index.js:54: 73)
最佳答案
这可能有多种原因:
具有相同 ClientId 的多个连接
clientId 一次只能用于一个连接。如果您在建立另一个连接时使用相同的 clientId 进行连接,则旧连接将被丢弃(这会导致过早关闭错误)并建立新连接。
The client is using a client ID that is already in use. In this case, the client that is already connected will be disconnected [...]. (Source)
权限
如果设备(来自 aws-iot-device-sdk-js 的 mqtt.Client)没有正确的权限来连接和/或发布/订阅/接收给定主题的消息,就会发生此错误。
有关更多文档,请参阅此处:https://docs.aws.amazon.com/iot/latest/developerguide/pub-sub-policy.html
策略应如下所示(示例显示 Cloudformation Iot Policy 资源):
MyIotThingsPolicy:
Type: AWS::IoT::Policy
Properties:
PolicyDocument:
Version: "2012-10-17"
Statement:
- Action: iot:Connect
Effect: Allow
Resource: !Join [ "", [!Sub "arn:aws:iot:${AWS::Region}:${AWS::AccountId}:client/",
"${iot:ClientId}"] ]
- Action: iot:Receive
Effect: Allow
Resource: !Join [ "", [!Sub "arn:aws:iot:${AWS::Region}:${AWS::AccountId}:topic/",
"${iot:ClientId}/eg/your/broadcast/topic"] ]
- Action: iot:Subscribe
Effect: Allow
Resource: !Join [ "", [!Sub "arn:aws:iot:${AWS::Region}:${AWS::AccountId}:topicfilter/",
"${iot:ClientId}/eg/your/broadcast/topic"] ]
- Action: iot:Publish
Effect: Allow
Resource: !Join [ "", [!Sub "arn:aws:iot:${AWS::Region}:${AWS::AccountId}:topic/",
"${iot:ClientId}/eg/your/publish/topic"] ]
!Join
是必要的,因为 Cloudformation 会尝试解析 ${iot:ClientId}
,这是一个运行时值,在部署期间未知。
疑难解答
作为Sandeep Patel还建议,如果你想在客户端对这种情况采取行动,你应该实现错误回调:
device.on('error', (error) => { // error.message might be 'premature close' });
您还可以查找
disconnectReason
关于主题$aws/events/presence/disconnected/<clientId>
,参见:https://docs.aws.amazon.com/iot/latest/developerguide/life-cycle-events.html
关于node.js - 如何解决 : premature close at onclosenexttick in Node. js 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59944783/