What is the process for establishing a connection between a websocket and an external API?

Currently, I have a route configured to fetch the weather data for a specific city using the openweathermap API

Here is the code snippet from my index.js file:

var express  = require("express"),
    router   = express.Router();
var weather = require("openweather-apis");

router.get("/weather", function(req, res){
  weather.setCity('Miami');
  weather.setAPPID(appID);
  weather.getAllWeather(function(err, allWeather){
    res.json({allWeather: allWeather});
  });
});

Now, I am looking to implement a websocket connection on this route so that I can receive real-time updates whenever there is a change in the data and show it to the users. Here's what I have tried:

From my index.ejs file:

<script src="https://cdn.jsdelivr.net/npm/socket.io-client@2/dist/socket.io.js"></script>
<script>
  var socket = io('http://localhost:3000/weather');
  socket.on('connect', function(){});
  socket.on('event', function(data){
   // do something
  });
  socket.on('disconnect', function(){});
</script>

Unfortunately, I keep encountering errors while attempting this setup. If anyone has insights on where I might be going wrong, I would greatly appreciate the assistance!

The error message I am receiving is as follows:

index.js:83 GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=Mzd4Dpj 404 (Not Found)

Answer №1

It is not possible to directly connect to a websocket server. The client establishes a connection with the websocket server, which does not actively establish connections on its own. (Note that a websocket client cannot connect to a standard HTTP endpoint).

If you aim to send data over a websocket whenever there are changes in the response from a traditional HTTP service, you would need to regularly check the service's URL (for example, using setInterval) and then dispatch the data via the websocket when new information is received.

The 404 error from

http://localhost:3000/socket.io/?EIO=3&transport=polling&t=Mzd4Dpj
indicates that there is no websocket provided on the server for client connection. To resolve this issue, refer to the getting started documentation for instructions on setting up the server-side components of Socket.io. Without the corresponding server setup, the client-side functionalities will not work properly.

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

Utilize Vue.JS to showcase JSON information from an external file

Currently, I have a View.JS app that displays a conversation thread from a JSON file. The existing code appears as follows: const app = new Vue({ el: "#app", data: { messages:[ { name: "Support", message: "Hey! Welcome to suppo ...

Deleting a DOM element within an element that has been created by an external script

On a webpage, I have third-party ad content that is generated by an external script. This content has a delay in loading. My goal is to eliminate a line break from the ad content, but this can only be done once the external script finishes loading and all ...

Can data be presented in AngularJS without the use of scope variables?

I have a method: <span ng-init="getJobApplicantsList(jobId)">(number should be display here)</span> Is there a way to display the data without having to store it in a scope variable? I need to use this method in many places. This is my cont ...

encountering a strange issue with session management in the Express framework

New to the express framework and currently working on the server.js file: // Dependencies. var application_root = __dirname, express = require( 'express' ), //Web framework path = require( 'path' ), //Utilities for handling file paths ...

Rendering content on the server side and creating a cached version of the index.html file using Vuejs and Nodejs

Having multiple websites (site1.com, site2.com) connected to a single server poses an interesting challenge. I am able to capture the domain name when a user enters a site, and based on that domain name, I fetch appropriate JSON data from an API to display ...

Guide on sending a JSON object to an EJS javascript loop efficiently

Seeking assistance with passing a Json object named myVar to the home.ejs file below. How should I assign the value to the variable called data? <table id="example" class="table table-striped table-bordered dataTable" cellspacing="0" width="100%"> ...

What is the best way to decrease the border width of a chartjs doughnut chart?

I have a vision for my chart based on the mockup: However, here is what I've been able to achieve using chartjs so far: This is the code I'm working with: datasets: [ { data: [3, 8, 13, 9, 2], backgroun ...

Ways to remove all attributes from a JSON data type

In my code, I am working with the following object: [ { "Name": "John Johnsson", "Adress": "Linkoping", "Id": 0, "Age": "43", "Role": "Software Engineer" }, { &qu ...

Middleware is encountering a request with missing user information

I've run into an issue where req.user is empty whenever I use the checkAdmin middleware in my routes Trying to create a middleware that checks if the user's role is ADMIN to allow them to create a new user, but it's failing. When the middle ...

What could be the reason for TypeScript being unable to recognize my function?

In my code, I have a Listener set up within an onInit method: google.maps.event.addListener(this.map, 'click', function(event) { console.log(event.latLng); var lt = event.latLng.lat; var ln = event.latLng.lng; co ...

Tips for modifying a user's tags with Quickblox's JavaScript SDK

Is there a way to update a user's tags using the Quickblox JavaScript SDK? I have attempted using the parameter names listed below: user_tags tags with var params = { user_tags: ["testing"] }; Kindly avoid suggesting alternatives like "custom ...

Using ExpressJS with the GET method to retrieve JSON data in conjunction with Angular version 4 and above

This inquiry may be a duplicate, I apologize for any repetition. My objective is to console.log JSON data from the "Server" folder. Please find the attached folder structure below. https://i.stack.imgur.com/uec4O.png server.js const express = require(&a ...

What is the best way to designate external dependencies in WebPack that are not imported using '*'?

I need assistance with specifying office-ui-fabric-react as an external dependency in my TypeScript project using Webpack. Currently, I am importing only the modules I require in my project: import { Dialog, DialogType, DialogFooter } from 'office-u ...

Sorry, I'm unable to determine the value of 'title' because it is undefined

Here is the code for the "singleCard" component. When passing {{card.title}} and {{card.body}}, an error occurs: **Error in render: "TypeError: Cannot read property 'title' of undefined" found in ---> <SingleCard> at src/components/sing ...

Guide to Incorporating a Marker into an SVG Blinking Rectangular or Circular Border Image on Google Maps

I have a link that points to a specific location on Google Maps using latitude and longitude: http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png Now, I am looking to add a blinking border to this marker link. Is there a way to achieve this ...

Exploring the concept of generator functions in ES6

I'm grappling with understanding JS generators and why the asynchronous operations in the example below are returning undefined. I thought that using yield was supposed to wait for asynchronous calls to finish. function getUsers(){ var users; $.aj ...

Transitioning Node JS code to Apollo server

Currently, I am in the process of configuring Apollo Server on my Node application and contemplating transferring the functionality over to Apollo. The current business logic I have looks like this: router.post( '/login', (req, res, nex ...

I'm attempting to utilize a basic webcam capture upload feature, but it seems that the upload function is not functioning properly

UPDATE: This is the complete code that I simply copied and pasted. <!DOCTYPE HTML> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script language="JavaScript" type="text/javascrip ...

Exploring the main directive flow, attaining access to `ctrl.$modelView` in AngularJS is

Four Methods Explained: What Works and What Doesn't I recently created an angular js directive where I encountered difficulty accessing the ctrl.$modelValue in the main flow. In my quest to find a solution, I came up with four potential methods, eac ...

What is the method for writing the following line in CSHTML server-side code?

<script> function a(id) { var table = document.getElementById(id); .... } </script> @{ //Is there a way to rewrite the line "var table = document.getElementById(id)" here within the ser ...