当websocket断开连接时,它没有通过queryStringParameters

时间:2019-12-28 05:49:49

标签: reactjs websocket aws-api-gateway

我已经使用AWS API GatewayAWS Lambda构建了Websocket API。

我可以很好地连接它,但是在断开连接时遇到了麻烦。

让我们看看代码。

我的React代码

import React from 'react';
import Sockette from 'sockette';

function socketHandler(uid) {
    const wss = new Sockette(`wss://MY_API_GATEWAY_URL.execute-api.ap-northeast-2.amazonaws.com/dev?groupId=GROUP_ID&uid=${uid}`, {
    timeout: 1000,
    maxAttempts: 10,
    onopen: (e: any) => { console.log(e); console.log('Websocket is connected') },
    onmessage: (e: any) => {
      console.log(e.data);
    },
    onclose: (e: any) => { console.log(e); console.log('Websocket is disconnected'); }
  });
  return wss;
}

const SocketForm = (props) => {
  const [socket, setSocket] = React.useState(null);
  const connect = () => {
    setSocket(socketHandler('MY_UID'));
  }
  const disconnect = () => {
    socket.close();
    setSocket(null);
  } 
  return(
    <div>
      <button onClick={connect}>Connect</button>
      <button onClick={disconnect}>Disconnect</button>
    </div>
  )
}

我的Lambda函数代码

export const connectionHandler = async (event) => {
  const { groupId, uid } = event.queryStringParameters; //It occurs ERROR with DISCONNECT

  if(event.requestContext.eventType === 'CONNECT'){
    // I can store connectionID with groupId and uid.
    // STORE connectionId to DB
  }else if(event.requestContext.eventType === 'DISCONNECT'){
    // DELETE connectionId from DB
  }
  return { statusCode: 200, body: JSON.stringify({}) }
}

我不知道为什么断开连接后它没有通过queryStringParameters

1 个答案:

答案 0 :(得分:0)

如果是python示例,能否在CONNECT中获取queryStringParameters

   if event["requestContext"]["eventType"] == "CONNECT":
    role = event["queryStringParameters"]["role"]
    logger.info(role)