Using ExpressJS to send SocketIO on a GET request

In my setup for an expressJS server with a socket.IO connection, the application continuously reads sensor data every 10 seconds and pushes it to all clients without any issues.

However, there is also a functionality where a client can call /set-status with parameters to update some status data. In this scenario, simply using a request/response approach won't work as the updated status data needs to be sent to all clients simultaneously.

So, what steps should I take to trigger the socketIO connection after the /set-status endpoint has been invoked?

const express = require('express')
const http = require('http')
const socketIo = require('socket.io')

const app = express()
const server = http.createServer(app)
const io = socketIo(server)

io.on('connection', socket => {
  getStatus(socket)
  getData(socket)
  setInterval(
    () => getData(socket),
    10000
  )
})

app.get('/set-status', (req, res) => {
  // Change some data and broadcast new data to all clients
  // How do I access the socket object?
  res.send(200, 'new-data')
})

const getStatus = async socket => {
  const res = { initial: 'data' }
  socket.emit('exampleStatus', res)
}

const getData = async socket => {
  // read some sensor data which updates every 10 seconds
  // this part works fine
  const res = { some: 'sensor data' }
  socket.emit('sensorData', res)
}

server.listen(port, () => {
  if (process.env.NODE_ENV !== 'production') {
    console.log(`Listening on port ${port}`)
  }
})

Answer №1

In order to notify client sockets about any changes in status, you can trigger an event called statusUpdate within your fetch function. Simply use the code io.emit('statusUpdate', data). Then, on the client side, set up a listener using

socket.on('statusUpdate', newData => // perform actions based on newData)
.

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

I'm struggling to resolve this recurring 404 error that arises whenever I try to access Ubuntu through an external port. The issue might be linked to Ubuntu, pm2, nginx, or express. Any suggestions on

Whenever I try to access my Ubuntu server by typing in my IP address on Chrome, I receive a web page titled "404 - Not Found". This issue persists whether I use my IP address directly or through my domain wwww.mydomain.com. Initially, I suspected an nginx ...

Attempting to pass a value to a data table using the Tabulator library within a Laravel 5.4 environment

Currently, I am trying to pass a value from a controller to a view in the following manner: use App\Products; use Illuminate\Http\Request; class MyController extends Controller public function index() { $main = Products::all(); ...

What is the method for inputting multi-line strings in the REST Client extension for Visual Studio Code?

Clarification There seems to be some confusion regarding the nature of the data I am storing. I am developing a code snippet web application using Express.js and MongoDB. The purpose is not to store executable code for later use; instead, I am saving snipp ...

Parsing a JSON object in JavaScript: A step-by-step guide

Looking for assistance on how to parse the JSON object below: { "info": [ { "systemIp": "192.168.1.1", "status": "done 956" }, { "systemIp": "192.153.1.1", "status": "done" } ] } Does anyone have a solution using Javascript or jQuery? The desired output ...

Initial request fails to retrieve cookie generated by Javascript

I created a shopping cart that generates a cart, adds items, and stores it in a cookie named 'cart'. However, when I click on a hyperlink that leads to the checkout page, my ASP.NET application is unable to access the cookie. The cookie only get ...

Toggle all debugger points at once in Chrome's web inspector

Can I quickly toggle all debugger points on or off, or bookmark all debug points at once in Chrome? ...

I am experiencing issues with my basic website, specifically with the functionality of my articles not meeting my expectations

Can anybody provide some assistance? I have a total of four articles that I would like to organize in the following manner: first one second one third one fourth one But for some reason, I am ...

Using JavaScript to access the Skyscanner API yielded a response with the error message indicating that the 'Access-Control-Allow-Origin' header was missing

After implementing the Skyscanner Api to create a session, I received a 201 response indicating that the session was successfully created. However, my script encountered an exception which halted its execution: "No 'Access-Control-Allow-Origin' h ...

Iterate through the JSON response and send it back to Jquery

I'm almost done with my first jQuery autocomplete script and just need some assistance in understanding how to make the found elements clickable as links. Here is a snippet of my JavaScript code: $(document).ready(function() { var attr = $(&apos ...

Drop-down functionality in Bootstrap Form becomes unresponsive after screen width is decreased

I recently encountered a strange issue with my simple Bootstrap form. When I resize my browser width to mobile size or view it on a mobile device, the form stops functioning properly. Unfortunately, I am unable to provide any specific code examples at this ...

Properly handling the use of single and double quotation marks in variable declarations within a JavaScript file

I have a search box where users can enter their search text. For example, they can type book, 'book', or "book". The value entered in the search box is then assigned to a variable in the JavaScript file. var searchTerm = "${searchTerm}"; <br/ ...

Ways to generate a customized template using the directive attribute parameter

I have developed a new directive and I am looking to incorporate a dynamic template using the attribute wm.data.typeName. wm.data.typeName = "<span>html code</span>" <fill-choose model-input="wm.data.modelInput" text="wm.data.typeName"&g ...

What are the implications of generating a JWT Token after logging in as opposed to after registering an account?

I've been developing a multi-page application using ExpressJS. Recently, I encountered a dilemma regarding the generation of JWT tokens upon login as opposed to during registration and whether there are any notable differences between the two approach ...

What is causing the Invalid left-hand side error in the postfix expression at this specific line of code?

I encountered an error stating "invalid left-hand side in postfix expression" while trying to execute this particular line of code data: 'Action=AutionMaxBid&AuctionItemID='+<?php echo $bidItemID ;?>+'', This error occurred d ...

Instructions for ordering this jQuery script that executes ajax and should return a 'true' value

In my javascript for form validation, I have added a new layer that calls an external function to send an Ajax request with the form validation results. The goal is to receive an email indicating whether the user passed or failed the validation. While cal ...

"The implementation of jQuery AJAX with asynchronous calls is failing to function as expected

Here is the JavaScript code snippet: function fetchData(param1,param2) { $.ajaxSetup({async:false}); var request = $.ajax({ url: "http://someurl.com/xyz.php?p1="+param1+"&p2="+param2, type: "POST", async: false, ...

What is the best way to apply css styles to buttons in Leaflet?

Trying to customize the CSS for the zoom buttons in Leaflet, but unable to assign a class or id. How can I access them? Any suggestions? Thanks! Map declaration: L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={acces ...

Adding Data using JavaScript in SAP HANA Express 2.0

Currently, I am in the process of learning SAP and encountering some challenges with HANA DB as a beginner. I am interested in adding data to a database using Javascript/HTML5-App, but have been unable to locate a suitable tutorial. I am utilizing SAP HA ...

Google Chrome is unable to process Jquery JSON .each() function

My website has a simple chat application that is functioning well. It uses ajax to request data in this manner: $.ajax({ url: "fetch/"+CHAT_SESSION_ID+"/"+LAST_MESSAGE_ID, dataType: "json", cache: false, success: function(data) { if (data.session_ac ...

What is the recommended location to put clearTimeOut?

Attempting the following var timeoutId = setTimeout(function() { if ("comboFilters[Agencies]" in partDic) { var agency = partDic["comboFilters[Agencies]"].substring(1); $('.Agency .dropdown-toggle').html(agency).append(' ...