最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - Socket IO usage with Strapi Typescript - Stack Overflow

programmeradmin3浏览0评论

I am trying to use SocketIO between my react front end and strapi backend.

What i have done is the following:

import { Core } from '@strapi/strapi';



export default {
  /**
   * An asynchronous register function that runs before
   * your application is initialized.
   *
   * This gives you an opportunity to extend code.
   */
  register(/* { strapi }: { strapi: Core.Strapi } */) { },

  /**
   * An asynchronous bootstrap function that runs before
   * your application gets started.
   *
   * This gives you an opportunity to set up your data model,
   * run jobs, or perform some special logic.
   */
  bootstrap({ strapi }: { strapi: Core.Strapi }) {
    let interval: NodeJS.Timeout;
    var io = require('socket.io')(strapi.server.httpServer, {
      cors: {
        origin: "*",
        methods: ["GET", "POST"]
      }
    });


    io.use(async (socket, next) => {
      try {
        //Socket Authentication

        const token = socket.handshake.headers.authorization;
        if (!token) {
          return next(new Error('Authentication error'));
        }
        console.log("token: ", token);
        let result = await strapi.plugins[
          'users-permissions'
        ].services.jwt.verify(token);
        //Save the User ID to the socket connection
        // socket.user = result.id;
        console.log("result: ", result);
        next();
      } catch (error) {

        console.log(error)
      }
    }).on('connection', function (socket) { });


    io.on('connection', function (socket) {
      if (interval) clearInterval(interval);
      console.log('User connected');

      interval = setInterval(() => io.emit('serverTime', { time: new Date().getTime() }), 1000);

      socket.on('disconnect', () => {
        console.log('user disconnected');
        clearInterval(interval);
      });
    });

    
    strapi.io = io; //This is the code that is not working
  },
};

I am following this tutorial:

however the error I am getting is:

Property 'io' does not exist on type 'Strapi'.ts(2339)

My Strapi version is: 5.8.1

What am I missing?

Thank you

发布评论

评论列表(0)

  1. 暂无评论