aws-amplify PubSub.publish TypeError: Cannot read property 'byteLength' of undefined

aws-amplify PubSub.publish TypeError: Cannot read property 'byteLength' of undefined

我正在尝试访问 aws-amplify PubSub.publish 以发布到 AWS IoT Core 中的主题。我正在使用 "aws-amplify": "2.1.0".

版本
handleSubmit = async () => {
    await PubSub.publish('topic', { msg: 'Hello to all subscribers!' });
};

我的aws-exports.js文件配置如下。

const awsmobile = {
    "aws_project_region": "us-east-2",
    "aws_cognito_region": "us-east-2",
    "aws_user_pools_id": "poolid",
    "aws_user_pools_web_client_id": "webclientid",
    "aws_cognito_identity_pool_id": "identitypoolid",
    "oauth": {}
};

export default awsmobile;

单击按钮调用 handleSubmit 函数,PubSub.publish 出现以下错误。

Uncaught (in promise) TypeError: Cannot read property 'byteLength' of undefined
    at Object.isEmptyData (browserHashUtils.js:30)
    at Hmac.push../node_modules/aws-sdk/lib/browserHmac.js.Hmac.update (browserHmac.js:34)
    at encrypt (Signer.js:50)
    at get_signing_key (Signer.js:222)
    at Function.Signer.signUrl (Signer.js:374)
    at AWSIoTProvider.<anonymous> (AWSIotProvider.js:233)
    at step (AWSIotProvider.js:152)
    at Object.next (AWSIotProvider.js:83)
    at fulfilled (AWSIotProvider.js:37)

这是由于未正确配置 Amplify PubSub Provider 造成的。

我的错误配置:

Amplify.addPluggable(new AWSIoTProvider({
  aws_pubsub_region: process.env.region,
  aws_pubsub_endpoint: `wss://${process.env.REACT_APP_MQTT_ID}.iot.${process.env.REACT_APP_REGION}.amazonaws.com/mqtt`,
}));

这里我没有设置process.env.region环境变量。这导致了错误。将其更改为适当的环境变量 (process.env.REACT_APP_REGION) 解决了这个问题。

工作配置:

Amplify.addPluggable(new AWSIoTProvider({
  aws_pubsub_region: process.env.REACT_APP_REGION,
  aws_pubsub_endpoint: `wss://${process.env.REACT_APP_MQTT_ID}.iot.${process.env.REACT_APP_REGION}.amazonaws.com/mqtt`,
}));