Welcome to the Linux Foundation Forum!

Cannot get the WebSockets example working

cfinis
cfinis Posts: 1
edited June 26 in LFW111 Class Forum

Hello,
I'm running the LFW111 course examples on node 20.11.0 with

  "dependencies": {
    "@fastify/autoload": "^5.0.0",
    "@fastify/cors": "^9.0.1",
    "@fastify/sensible": "^5.0.0",
    "@fastify/websocket": "^10.0.1",
    "fastify": "^4.26.1",
    "fastify-cli": "^6.2.1",
    "fastify-plugin": "^4.0.0"
  },

The Web Sockets example in lesson 04 (Going Realtime) doesn't work for me. When I run the mock-service, and select a category in the static web page, the mock service of the routes/orders plugin throws an error complaining that the socket is undefined:

[16:45:38.506] ERROR (369197): Cannot read properties of undefined (reading 'send')
    reqId: "req-2"
    err: {
      "type": "TypeError",
      "message": "Cannot read properties of undefined (reading 'send')",
      "stack":
          TypeError: Cannot read properties of undefined (reading 'send')
              at Object.<anonymous> (file:///home/cfinis/workspace/jsnad/my-project-WS/mock-srv/routes/orders/index.mjs:9:16)
              at /home/cfinis/workspace/jsnad/my-project-WS/mock-srv/node_modules/@fastify/websocket/index.js:185:34
...
}

Any idea what is going wrong?

Thanks

Answers

  • dwloughran
    dwloughran Posts: 2

    I've got the same problem. Did you ever get it working?

  • dwloughran
    dwloughran Posts: 2

    @jonatasmello , thank you! That was the problem.

  • kdhyne
    kdhyne Posts: 1

    Saved my sanity with this, thanks!

  • Thanks @jonatasmello. Could the admins fix this? Also, there is a minor bug on the related page https://trainingportal.linuxfoundation.org/learn/course/introduction-to-nodejs-lfw111x/going-real-time/real-time-functionality?page=4 -> the static files should be served with command npx serve -p 5050 static

  • @jonatasmello Thanks it worked.

  • @jonatasmello said:
    Hi,
    here is what worked for me based on the official documentation

    async ({ socket }, request) => {

    use this instead:

    async ( socket, request) => {

    the parameter "socket" is just a variable, not an object (with {socket} )

    Let's also create an index.mjs file in our newly created folder with the following contents:
    
    "use strict";
    
    export default async function (fastify, opts) {
      fastify.get(
        "/:category",
        { websocket: true },
        async (socket, request) => {
          socket.send(JSON.stringify({ id: "A1", total: 3 }));
        }
      )};
    

    This is the miracle working code!! A crack!!

  • strdpl
    strdpl Posts: 1

    Grazie!

Categories

Upcoming Training