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

The way in which notifications for updates are displayed on the Stack Overflow website

Could someone shed some light on how the real-time update messages on this platform are created? For instance, when I am composing a response to a question and a new answer is added, I receive a notification message at the top of the page. How is this fun ...

When transferring JavaScript Array via Ajax to PHP, it results in a null response

I am attempting to send a JavaScript array to PHP, but the post data keeps returning null. Here is my JavaScript code: console.log($Seats); console.log($Seats.toString()); console.log(JSON.stringify({ $Seats })); var jsonStr = JSON.stringify($Seats); $.a ...

Inadvertent scroll actions causing unexpected value changes in Material UI sliders

I am currently working on a React application that utilizes Material UI, with slider components integrated throughout the interface. However, I have encountered an issue when using a touch screen device - unintentional changes to the slider values occur wh ...

Creating a prompt within a while loop

Issue with the code is that it should only progress if the user inputs "rock", "paper" or "scissors". However, after re-entering any input the second time, it still moves on despite passing the condition in the while loop. For instance, entering "asdf" p ...

Issue: unable to establish a connection to [localhost:27017]

Upon executing node app.js, an error message is displayed: Failed to load c++ bson extension, using pure JS version Express server listening on port 3000 events.js:85 throw er; // Unhandled 'error' event ^ Error: failed to conn ...

Regex pattern is malfunctioning

I am having trouble understanding why this regex keeps returning false. I have an onkeydown event that should trigger it when pressing the 'w' key, but it doesn't seem to be working. var keyGLOB = ''; function editProductSearch ( ...

Implementing custom logic in a Vuetify dialog box

Is it possible to trigger a dialog on a button click while executing some logic before and after the event? How can this be accomplished? Here is what I have attempted: template <v-dialog v-model="dialog" width="400"> <template v-slot:activat ...

Ways to transfer a state from the child component to the app component

I have 2 different components that contain sub-components within them. In one of these components, I'm trying to figure out how to transfer the click event from the sub-component to another component so that it can render an entirely new component for ...

What is the best way to transfer data from an AJAX GET request to a Node.js GET route?

Here is an example of an ajax request being made $.ajax({ url: '/reload', type: 'GET', contentType: "application/json", data: { Name: $("#inputName").val(), Link: $("#inputLink").val() }, succe ...

Exploring the vue.prototype object within a component's scope

Recently in my main.js file, I added the line: Vue.prototype.api_url = 'http://localhost' and then in one of my components called dashboard.vue I implemented the beforeRouteEnter export default { data() { return { } }, beforeRouteEnter ...

Using jsdom as a package in a Meteor application is not possible

Recently, I came across an issue with my packages.json file. It looks like this: { "jsdom" : "0.8.0", "request" : "2.25.0" } As part of my project, I have the following code snippet: if (Meteor.isServer) { Meteor.startup(function () { var _ ...

Node's getRandomValues() function is throwing an "expected Uint8Array" error

Currently, I am experimenting with the getRandomValues() function to enhance an encryption REST API that I am developing for practice. My server is using Node, which means I do not have access to a window object containing the crypto object normally housin ...

Generate dynamic Bootstrap Carousel slides with unique hashtag URLs

I've been attempting to connect to various slides within a bootstrap carousel from a different page but have had no success. Here is an example of what I'm trying to achieve: <a href="services#slide2">Link to Slide 2</a> For refere ...

I must extract all the information from the webpage within the HTML tags, however, I am unsure of which specific tag to target for the data extraction

Here is the example of HTML code that includes a price: <meta itemprop="price" content="121080"> I have created this search code, but I am unsure which tag to use for finding the price: const puppeteer = require('puppeteer&a ...

Regex substitute every instance of the phrase CONTAINED within brackets

I am looking to replace all instances of text within brackets, including the brackets themselves, in a given string. The specific text to be replaced will be stored in a variable in Javascript. Using a simple regex in a replace method won't work due t ...

When attempting to import and utilize global state in a component, the error message "Cannot iterate over null object"

I am in the process of setting up a global state to keep track of various properties that I need to pass down to multiple components. const initialState = { username: '', selectedCategory: null, categoriesList: [], createdTaskTopi ...

jQuery Refuses to Perform Animation

I'm facing an issue with animating a specific element using jQuery while scrolling down the page. My goal is to change the background color of the element from transparent to black, but so far, my attempts have been unsuccessful. Can someone please pr ...

Having trouble with dynamic CSS not functioning properly when a checkbox is changed in Vue.js

I'm currently attempting to dynamically adjust the css styling of specific text within a span element by utilizing v-on:change on a checkbox. However, I am encountering an issue where the styling does not update as expected, and I am struggling to ide ...

Tips for sending form data from ReactJS to controller in ASP.NET MVC:

Seeking help with React and ASP.NET integration. I am attempting to create a form in ASP.NET using React, but encountering issues when trying to pass form data from ReactJS to an MVC ASP.NET controller. Below is the code that I have been working on. Any su ...

picking out a particular set of data from a JSON document

I have a map of Europe along with a JSON file that displays the unemployment rate for each country in the year 2011. The JSON file also includes x and y elements, allowing me to place a blue circle on top of each country on the map. My goal is to be able ...