uNetworking / uWebSockets.js

μWebSockets for Node.js back-ends :metal:
Apache License 2.0
7.82k stars 568 forks source link

.getUserData() on WebSocket<HttpRequest> does not return the UserData #1085

Closed leeian1011 closed 1 month ago

leeian1011 commented 1 month ago

uWS.js Version: v20.44.0 node version: v20.5.1

Description: When attempting to retrieve the UserData generic from the WebSocket class by calling the getUserData() method, the returned value is the UserData type but the WebSocket type.

Simple reproducible example:

import { App, DISABLED, HttpRequest, TemplatedApp, WebSocket, HttpResponse, us_socket_context_t } from "uWebSockets.js";

class WebSocketServer {
  private readonly _websocket: TemplatedApp

  constructor() {

    this._websocket = App().ws('/*', {
      upgrade(res: HttpResponse, req: HttpRequest, context: us_socket_context_t) {
        console.log(req)
        console.log(req.getHeader('x-forwarded-for'))
        res.upgrade(
          { req },
          req.getHeader('sec-websocket-key'),
          req.getHeader('sec-websocket-protocol'),
          req.getHeader('sec-websocket-extensions'),
          context
        )
      },
      message(ws: WebSocket<HttpRequest>, message) {
        const req = ws.getUserData()
        console.log(req)
        console.log(req.getHeader('x-forwarded-for'))
      },
    })
  }

  public async start(port: number) {
    await new Promise<void>((resolve, reject) => {
      try {
        this._websocket.listen(port, (socket) => {
          if (socket) {
            resolve();
          } else {
            console.error("Failed to setup socket for listening.")
            reject("Failed to setup socket for listening.");
          }
        })
      } catch (e) {
        reject(e)
      }
    }).catch((e) => {
      console.error(`Caught Execption ${e}`)
    })
  }
}

const server = new WebSocketServer()

await server.start(7000)

Expected result:

uWS.HttpRequest {}
127.0.0.1
uWS.HttpRequest {}
127.0.0.1

Actual result: image

uNetworkingAB commented 1 month ago

You can't pass along HttpRequest either way. You can look at Upgrade example

uNetworkingAB commented 1 month ago

https://github.com/uNetworking/uWebSockets.js/blob/master/examples/Upgrade.js

leeian1011 commented 1 month ago

I see, this has helped. Thank you