NodeJS 如何使用uWebSocket.js从API获取Body?

xiozqbni  于 2023-03-01  发布在  Node.js
关注(0)|答案(1)|浏览(148)

我正在使用uWebSocket.js并尝试从API获取有效负载。我已检查its official GitHub site related to routes
我检查并实现了所有的方式解释,它的工作很好。但是,我面临的问题,以获取身体数据从后方法
我尝试的是...

let app = uWS
    ./*SSL*/App()
    .post('/login', (res, req) => {
        console.log(req.body); 
        res.end(JSON.stringify({ message: 'Nothing to see here!' }));
    })
    .ws('/*', {
        /* Options */
        compression: uWS.SHARED_COMPRESSOR,
        maxPayloadLength: 16 * 1024 * 1024,
        idleTimeout: 10 * 4,
        maxBackpressure: 1024,
        open: (ws) => {
            /* Let this client listen to topic "broadcast" */
            
        },
        message: (ws, message, isBinary) => {
            
        },
        drain: (ws) => { },
        close: (ws, code, message) => {
            
        }
    })
    .listen(port, (token) => {
        if (token) {
            console.log('Listening to port ' + port);
        } else {
            console.log('Failed to listen to port ' + port);
        }
    });
kmbjn2e3

kmbjn2e31#

您应该使用此处提到的www.example.com方法www.example.com res.data method as mentioned here https://github.com/uNetworking/uWebSockets/issues/805#issuecomment-451800768
下面是一个例子

.post("/short", (res, req) => {
  res
    .onData((data) => {
      const stringed = handleArrayBuffer(data);
      console.log("stringed received", stringed);
    })
    res.write("Great knowing you");
    res.writeStatus("200OK");
    res.end();
})

上面接收到的数据将作为数组缓冲区进入,因此您可能希望将其解码为如下字符串

export const handleArrayBuffer = (message: ArrayBuffer | string) => {
  if (message instanceof ArrayBuffer) {
    const decoder = new TextDecoder();
    return decoder.decode(message);
  }
  return message;
};

相关问题