在AWS ApiGatewayV2 Websocket连接上进行HTTPs请求以响应或删除它

5

更新

这个问题已经部分解决,现在的问题在于验证ApiGateway请求。我不确定如何获取必要的令牌以便与请求一起发送,以使其有效,因为这是一个[无服务器框架]服务,所以我无法使用AWS控制台将令牌复制粘贴到请求的JSON数据中。此外,我也不知道它们应该放在哪个JSON键下。所以我想这个问题的范围已经发生了相当大的变化。


我需要在Lambda函数中响应/删除通过AWS ApiGatewayV2建立的活动WebSocket连接。如何使用node js发送一个ApiGateway可以理解的POST请求?
我在websocket支持公告视频上看到,您可以发出HTTP POST请求来响应WebSocket,并发出DELETE请求来断开WebSocket连接。以下是视频转录的完整表格:
Connection URL
https://abcdef.execute-api.us-west-1.amazonaws.com/env/@connections/connectionId

Operation  Action
POST       Sends a message from the Server to connected WS Client
GET        Gets the latest connection status of the connected WS Client
DELETE     Disconnect the connected client from the WS connection

我所知道的,这并没有在其他地方有详细记录。

由于AWS SDK在ApiGatewayManagementApi上没有提供deleteConnection方法,因此我仍然需要直接向ApiGateway发出请求。

const connect = async (event, context) => {
  const connection_id = event.requestContext.connectionId;
  const host = event.requestContext.domainName;
  const path = '/' + event.requestContext.stage + '/@connections/';
  const json = JSON.stringify({data: "hello world!"});

  console.log("send to " + host + path + connection_id + ":\n" + json);

  await new Promise((resolve, reject) => {
    const options = {
      host: host,
      port: '443',
      path: path + connection_id,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(json)
      }
    };
    const req = https.request(
      options,
      (res) => {
        res.on('data', (data) => {
          console.error(data.toString());
        });
        res.on('end', () => {
          console.error("request finished");
          resolve();
        });
        res.on('error', (error) => {
          console.error(error, error.stack);
          reject();
        });
      }
    );
    req.write(json);
    req.end();
  });
  return success;
};

当我使用 wscat 进行测试时,此代码会导致 console.log 在 CloudWatch 中显示:
send to ********.execute-api.us-east-2.amazonaws.com/dev/@connections/*************:
{
    "data": "hello world!"
}

...

{
    "message": "Missing Authentication Token"
}

...

request finished

wscat 说:

connected (press CTRL+C to quit)
>

但是并没有打印出“hello world!”或类似的内容。

编辑

我漏掉了

res.on('data', (data) => {
  console.error(data.toString());
});

在响应处理程序中,出现了破坏事物的情况。然而,这仍然不起作用。

你的 serverless.yml 长什么样?你介意把它添加到你的问题中吗? - 0x6C38
1个回答

3

谢谢您的回答,我已经看过这个文档页面,但它遗漏了评论中最关键的部分:// Do a SigV4 and then make the call。也许我错过了一些明显的方法来做到这一点?关于Lambda权限,我认为我已经正确设置了它,因为我使用serverless-framework来完成它。(我认为这是自动的?) - vero
1
您可以使用像 aws4 这样的 NPM 包来生成 sig4 请求。 - Centinul
非常感谢,这正是我所需要的! - vero

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接