Exploring the possibilities of socket.io-client in combination with Vite.js and Vue for seamless real

I am currently diving into socket.io for my upcoming Vue project, but I seem to be encountering some issues. Interestingly, everything works smoothly when I use vue-cli, however, I prefer working with Vite.js due to its speed and customization options. Unfortunately, when I attempt to integrate socket.io with vite, I keep seeing it disconnected in the console. It seems there might be a conflict between esbuild and commonjs. I even tried using vite-plugin-commonjs to support commonjs modules but ran into the same issue.

I've copied and pasted my code from vue-cli to Vite, where it works flawlessly in vue-cli but remains disconnected in Vite.

This is my server-side code:

const express = require("express");
const socket = require("socket.io");
const app = express();

const server = app.listen(3001, function () {
  console.log("server running on port 3001");
});

const io = socket(server, {
  cors: {
    origin: "*",
  },
});

io.on("connection", function (socket) {
  console.log(socket.id);
  socket.on("SEND_MESSAGE", function (data) {
    io.emit("MESSAGE", data);
  });
});

This is my frontend (Vue) code:

<template>
  <button @click="echo">Echo</button>
</template>

<script>
import { io } from "socket.io-client";
export default {
  data() {
    return {
      socket: io("http://localhost:3001"),
    };
  },
  methods: {
    echo() {
      console.log(this.socket.disconnected);
    },
  },
};
</script>

Thank you in advance for any assistance!

Answer №1

Upon not finding your package.json file for a Vite project, I created a new project using the command

npm init vite@latest my-vue-app --template vue

I then installed vue-socket.io with this command npm install vue-socket.io --save

Here is the functioning code:

Vue code:

<template>
  <button @click="echo">Echo</button>
</template>

<script>
import VueSocketIO from "vue-socket.io";
export default {
  data() {
    return {
      socket: new VueSocketIO({
            debug: true,
            connection: 'http://localhost:3001'
      })
    }
  },
  methods: {
    async echo() {
      console.log(this.socket.io.connected); // prints true
    },
  },
};
</script>

Server code:

const express = require("express");
const socket = require("socket.io");
const app = express();

const server = app.listen(3001, function () {
    console.log("server running on port 3001");
});

const io = socket(server, {
    allowEIO3: true,
    cors: {credentials: true, origin: 'http://localhost:3000'},
});

io.on("connection", function (socket) {
    console.log(socket.id);
    socket.on("SEND_MESSAGE", function (data) {
        io.emit("MESSAGE", data);
    });
});

Everything is functioning properly. You can also run Node.js SocketIO in debug mode by using this command

DEBUG=socket* node {ENTRY FILE NAME}.js

Please let me know if everything is working as expected :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What strategies can I employ to address this historical issue?

Encountered TypeError: (0 , history_history__WEBPACK_IMPORTED_MODULE_6_.default) is not a function This issue arises in my history.js file import { createBrowserHistory } from 'history'; export default createBrowserHistory({ forceRefresh: tr ...

The latest version of Next.js, 11.1.0, does not support monitoring for code changes within the node

In the latest version of Nextjs (11.1.0), there seems to be an issue where code changes in the `node_modules` directory are not being watched, unlike in the previous version (10.2.1). While working on a project with Nextjs 11.1.0, I have tried explicitly ...

Ensure that you decode the URL before making any changes to the location in a

Hi everyone, I'm facing an issue and need your help. Let's say we have a URL like site.com/post?comments=1,2,3,4. When I paste it into the browser address bar, my app opens and decodes the URL to site.com/post?comments=1%2C2%2C3%2C4. How can I re ...

utilizing the .on method for dynamically inserted elements

I have a code snippet that triggers an AJAX request to another script and adds new <li> elements every time the "more" button is clicked. The code I am using is as follows: $(function(){ $('.more').on("click",function(){ var ID = $(th ...

Creating a Custom Class for a Custom Button in TinyMCE 4 Using addButton()

Is there a way to add a custom class to a custom button using the addButton() function in TinyMCE? Here is an example: editor.addButton('keywords', { text: 'Insert Keywords', class: 'MyCoolBtn', ...

Tips for hiding the overflow scrollbar on Microsoft Chrome when there is no content to scroll

Looking for a solution to hide scroll bars in Microsoft Chrome, but only when there is no content to scroll? The current div and styles always show the horizontal and vertical scroll bars, even when the height exceeds the content. <div style="backgroun ...

"Utilizing Jest Globals to Provide an Empty Input for a Function: A Step-by-

I have developed a function that outputs null when the input is empty: const testFunc = (param) => { if (param) { //blabla } return null; }; To verify the return null behavior with an empty param, I want to utilize describe...it...: describe( ...

DiscoverField Component with Button Functionality and Checkbox Dilemma

I'm working with Vue 3, Vuetify, and TypeScript for my searchField component. Inside, I have two buttons: FreeItemMaster and PatternMaster. Clicking on these buttons should change their background color and display respective content below them. Howev ...

Is it possible to call a Node.js function from JavaScript using a <script> tag in a Jade template?

I have been working on developing a blog using Node.js, Express, and MongoDB. In the template for creating a new post, there are fields for both a title and a slug. To generate slugs, I am utilizing the Slugs for Node.js library from NPM: https://npmjs.or ...

What is the proper way to showcase thumbnails in different sizes?

Currently, this is what I have: The display looks optimal with high-resolution landscape photos. This is the HTML and CSS code in use: <div class="upload-thumb ng-scope visible"> <span class="delete-media"> <span class="icon-bin ...

Present the retrieved JSON data values in an alternative layout on the table

I am facing an issue with the data display in my current table setup. The data is fetched from an SQL server, encoded into JSON format, and the structure of the JSON output is causing a problem for me. You can see how it looks like here: The challenge I a ...

JavaScript: Trouble with statement execution

My code is designed to classify a point as 1 if it's above the line y=x, and -1 if it's below the line y=x. I visually represent this line in a canvas by plotting y=x (although due to invertion on the y-axis, it appears like y=-x). For each point ...

What is the best way to add a new item to an object using its index value?

Can the Locations object have a new property added to it? The property to be added is: 2:{ name: "Japan", lat: 36, lng: 138, description: 'default', color: 'default', url: 'default' } The current Location ...

Conceal the button briefly when clicked

How can I disable a button on click for a few seconds, show an image during that time, and then hide the image and display the button again? HTML: <input type="submit" value="Submit" onclick="validate();" name="myButton" id="myButton"> <img st ...

Is there a way for me to display the image name at the bottom before uploading it, and have a new div created every time I upload an image?

Is there a way to display the image name at the bottom and have it create a new div every time an image is uploaded? I would appreciate any help with this... <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstra ...

Issue with mouse movement in Selenium and Protractor not functioning as expected

Greetings! I am currently facing an issue in my Angular application with Openlayers3 map integration. There is a layer representing a building on the map, and when I try to click on a building during testing, it should trigger a side panel displaying image ...

What is the recommended library for managing a task queue in this project?

Is there a library or package available for Node.js that can help me create a task queue with a fixed timeout between the start of each task and an overall callback that is triggered after all tasks have finished? https://i.stack.imgur.com/j1wCY.jpg ...

The compatibility between Babel 7 and the preset-es2015 is not very reliable

After reading this useful tutorial on implementing server-side rendering with create-react-app, I attempted to execute the following code snippet: require('ignore-styles'); require('babel-register')({ ignore: [/(node_modules)/], ...

Can you please explain the meaning of this error generated by npm-check-updates?

After attempting to start a new project with Vue 3, Vuetify 3, Vue-router, and Pinia, I navigated to my c:\Vue directory where I normally store my source code. From there, I ran the command npm create vuetify. Here's what happened: Vuetify.js - M ...

Attempting to retrieve an image from the database using ajax within a PHP script

I'm facing an issue with my code where I am attempting to retrieve an image from a database using AJAX, but it's not working as expected. Can someone please help me out? Image uploading works fine when trying to fetch the image using an anchor ta ...