Node.js Express is successfully receiving messages from the WebSocket server but encountering difficulties when attempting to send them out

My setup involves websockets with AWS API Gateway, an EC2 instance running Node.js and Express with WS websockets. I can send a message from wscat to the API Gateway WSS URL and it shows up in the EC2 instance. However, when I send a message from the EC2 instance, it doesn't show up back in wscat. I followed this tutorial to set up the API Gateway: https://aws.amazon.com/blogs/compute/announcing-websocket-apis-in-amazon-api-gateway/

Below is the code on my EC2 instance. I'm unsure of what might be causing the issue:

const express = require("express");
const app = express();
const port = 8080;
const WebSocket = require("ws");
const url = "wss://obsf.execute-api.us-east-1.amazonaws.com/Prod";
const ws = new WebSocket(url);

process.setMaxListeners(0) // I have tried with and without this line

app.get("/", (req, res) => {
  var test = { action: "sendmessage", data: "hello world" };

  ws.on("open", function open() {
    ws.send(JSON.stringify(test));
  });

  ws.on("message", function incoming(data) {
    console.log(data);
  });

  ws.on('error', (error) => {
    console.log(error)
  });

  res.send("Hello World!");
});

app.post("/doorbell", (req, res) => {
  console.log(req);
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

Updated Error Information:

I am encountering the following errors:

...

Update: After trying the addition of EventEmitter settings, I still face the EventEmitter error.

Further Update:

Moving the `ws.on("open")` event outside the `app.get` resolves the issue. I plan to test if placing it inside the `app.post` will result in the same error. Why is it problematic to have it in `app.get`?

Another Update:

Despite trying to include it in the post request, the event emitter error persists.

Answer №1

After receiving a response on the ws github issues, I thought it would be helpful to share the solution here for others.

app.post('/doorbell', (req, res) => {
  var message = { action: 'sendmessage', data: 'hello world from post request' };

  if (ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify(message));
    res.send('Hello there!');
  } else {
    res.send('The WebSocket connection is currently closed');
  }
});

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

how to pass arguments to module.exports in a Node.js application

I have created a code snippet to implement a Node.js REST API. app.js var connection = require('./database_connector'); connection.initalized(); // I need to pass the connection variable to the model var person_model = require('./mod ...

Is there a correlation between the length of the first argument in the socket.emit function of socket.io and latency?

I am intrigued by whether there is a distinction, other than readability, between code snippets like: socket.emit('m','something'); and socket.emit('chat message','something'); Is switching from the second option ...

Sending JavaScript objects from React.js to Node.js

I send the object to the backend (Node js) when making an API call, but I am logging the objects for verification. Initially, I used POSTMAN to check and it worked perfectly. However, when attempting to pass an object in the frontend (Reactjs), it appear ...

Inserting Array Type Values into Node.js and MongoDB

I need assistance with inserting array type values into the database. Currently, when I try to do so, it results in a blank array both in the database and when accessing req.body. Can someone please help me resolve this issue? Below is the method I am us ...

Are cookie-session and JWT tokens essentially the same thing in Express, or is there a difference between them?

When looking at the express documentation, you will come across a differentiation between express-session and cookie-session. The explanation provided is as follows: There are two main ways to store a user session with cookies: either on the server or on ...

What is the necessary step to configure the "basedir" option for Jade in an Express application? (This option is essential for utilizing "extends" with absolute paths)

As I work my way through the peepcode nodejs video and try to recreate the app using the latest express/node versions, I've encountered a minor issue. Here is the current file structure: site - apps - - authentication - - - views - - - - login.j ...

Creating a one-to-many relationship in Mongoose using array push operations

I have two collections: Projects and Developers. I can assign a single project to a developer, but I'm struggling with assigning multiple projects. Any suggestions on how to achieve this? Would using an array be the best approach for assigning multip ...

Discover the Mongoose Document and Arrange in a Random Order with Various Levels?

I am currently using a .find() method to sort documents in a collection based on their "status" and ordering them by most recent. Is it possible to first sort by status, and then randomly sort within each tier? For example, I have users divided into three ...

Regions for the MEAN stack

On our website, let's call it "www.xxxx.com," we need to develop a sub-portal dedicated to a specific company referred to as "www.xxxx.com/company1." This sub-portal should contain all the necessary controllers and views within an Area called "Company ...

Next.js is optimized for simplicity and ease-of-use, making it

I'm currently experimenting with integrating the Express Router in Next.js by utilizing their example of a custom-express-server as my starting point. My approach involves external route definitions in routes/router.js, which looks like this: Here is ...

Modify components in a web application based on the content of a JavaScript variable

I'm in the process of developing a webapp that needs to interact with an Arduino for its inputs in order to dynamically change the contents of the webpage. Currently, I am experimenting with variables that I have created and assigned random numbers t ...

Guide on sending data to MongoDB using Postman

I am currently facing an issue while trying to send data to the MongoDB database using Postman. Despite everything seeming fine, I keep encountering errors. https://i.stack.imgur.com/Gcf5Q.jpg https://i.stack.imgur.com/ntjwu.jpg https://i.stack.imgur.co ...

The pdfkit library seems to have an issue where it is failing to properly embed images within the

Currently, I am working on using PDFkit along with node.js for converting an HTML webpage into a PDF format. The HTML page contains multiple image tags within the body tag. Unfortunately, when I convert the HTML to PDF, the resulting page appears complete ...

What could be causing my Fetch GET Request to hang in Node.js?

Having trouble with the getDocuments request in my code. It never seems to complete and stays pending indefinitely. What could be causing this issue? App.js import React, { useState, useEffect } from 'react'; import Grid from './Grid'; ...

Importance of having both package.json and package-lock.json files in an Angular project

As a newcomer to Angular, I recently installed a sample app using angular-cli and noticed the presence of both package.json and package-lock.json files. The package-lock.json file contains specific dependencies, while the package.json file includes other i ...

Warning: Unhandled promise rejection - Issue with casting data

I'm encountering an issue when attempting to access one of my routes using a GET request. Shown below is my Item model: models/item.js const { Schema, model } = require('mongoose'); const ItemSchema = new Schema({ name: { type: ...

What is the preferred method of compiling Sass: utilizing the Live Sass Compiler extension in VS Code, or setting up and running Sass through npm? (Including guidance on transitioning from node-sass to dart-sass)

As I delve into an online course focused on Advanced CSS and Sass, I have noticed that the techniques being taught seem a bit outdated. The course heavily relies on node-sass in its dependencies, which is now considered deprecated. An alternative solution ...

Express Generator neglects specified port configuration

Here's the code I'm using to set the port to 3004 in my express generator app, placed right above module.exports = app;: // app.js const PORT = 3004; app.set('port', PORT); app.listen(PORT, () => { console.log(`app listening on ...

Can Node.js cli options be permanently set as default?

Is there a way to set default CLI options for all npm scripts in a project? I'm looking to ensure that every npm script in my project runs with the CLI option --unhandled-rejections=strict. Is there an official method for achieving this? ...

Encountering an Invalid Host header while connecting a domain name with a reactjs application

Currently, I am in the process of deploying a JS application (with the backend in nodejs and front-end in reactjs) on a hosting server. To ensure smooth operation, I have dockerized all components including the back end, front end, and database. As of now, ...