Is there a way to detect when a user disconnects from an express server?

I've set up a node express server to power an instant chat feature on my website. One issue I'm facing is that when a user closes their browser, their status doesn't change to 'offline' on their friend's buddy list. I know there's a function in node called req.on('close', function(){}); but I'm unsure how to integrate it into my server file. Any tips or guidance would be highly appreciated. Below is a snippet of relevant code from my express server:

var app = express();
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.bodyParser());    
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});

app.use(require('./middleware/im')({
maxAge: 60 * 1000,
reapInterval: 60 * 1000,
    authentication: require('./libs/authentication/' + AUTH_LIBRARY) 
}));


    app.set('root', __dirname);

// Listener endpoint; handled in middleware app.get('/listen', function(){});

app.post('/message', function(req, res) {
    res.find(req.body['to'], function(user) {
        if(!user)
           return res.send(new packages.Error('not online'));
        res.message(user, new packages.Message(
        req.session.data('username'),
        req.body.body
    ));


});

});

});

If you come across any issues while using the above code, feel free to seek further advice from the community.

Answer №1

HTTP, being a stateless protocol, does not keep track of individual users connected to a server. To handle user navigation events, you can utilize client-side mechanisms such as an onbeforeunload handler that sends a message to the server. The mention of the close event may not be relevant unless you are using long-polling techniques.

For implementing real-time chat functionality, a more efficient approach could involve using technologies like socket.io. This library enables a continuous connection between the browser and the server, with built-in features for detecting when a connection is closed by the browser (e.g., if the user navigates away).

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

Damaged .xlsx document originating from a Flask web application and an ajax POST submission

I've encountered an issue with my Flask web app where a URL route receives a post request containing JSON, converts it to an .xlsx file, and returns it using send_file(). On the server side, the generated .xlsx file appears to be correct. However, wh ...

Managing alerts in Python Selenium

I am encountering an issue while trying to handle a pop-up alert after a file upload. Despite using the code snippet below, I am receiving the error message shown. https://i.sstatic.net/Gqg8v.png wait.until(EC.alert_is_present()) driver.switch_to.alert() ...

What is the best way to utilize JQuery AJAX to send XML data for a delete request?

I am having trouble sending XML type data to the backend using jQuery and AJAX as a DELETE request. When I do this, I receive an empty array from the backend's request body. How can I properly send the ID? Below is the code I am using: function delet ...

Retrieve the current language from a non-page component on the server side with the help of Next.js and the next-i18next

I am working on a nextjs application that utilizes the next-i18next library for internationalization. I'm struggling to figure out how to access the current language on the server-side within a component that is not a page. On the server side, you ca ...

How to access nested JSON elements in Javascript without relying on the eval function

Below is a JSON that I am trying to access. { "orders": { "errorData": { "errors": { "error": [ { "code": "ERROR_01", "description": "API service is down" } ] } }, "status": " ...

Capture all URLs containing [...slug] and generate static props only for valid addresses in Next.js

I am utilizing dynamic routes with the fallback:true option to ensure newly created pages are accepted. First, I check if the parameters are true, then I create related props and display the component with those props. In the console, I can observe that Ne ...

Tips for incorporating a return statement within a network request function that is already returning information pertaining to the request

Is there a way to retrieve the data extracted from within newReq.on('response', (response) => {? var request = require('request'); const cheerio = require('cheerio'); const { app, net, BrowserWindow } = require('elect ...

Exploring the concept of jQuery handler functions

Within my code, I have the following: <script type="text/javascript"> $(document).ready(function (e) { $('#EventCreate').click(function (e) { location.href = '@Url.Action("Create", "AEvents")'; }); ...

Establish a global variable within the utils.js module in a Node.js environment

Hey there, I'm currently in the process of trying to figure out how to properly define a global variable in node.js. I am aware that it's not considered best practice, but in this specific scenario, it seems like the only way to go without involv ...

Struggling to get your function to complete its execution due to asynchronous operations?

The code in the comment block is not functioning properly when placed inside an if statement. It seems that the issue may be related to its position before a return statement, so I am looking for a way to ensure it completes running before the return is c ...

Why do attributes of a directive fail to function within a different directive in AngularJS?

Trying to set attributes of the angularJS directive named ng-FitText within another angularJS directive called scroll-cards. Here's the approach I'm taking: In the code snippet below, the attribute data-fittest is being assigned from ng-FitText ...

The React class component is throwing an unexpected error with the keyword 'this'

I encountered an error stating "Unexpected keyword 'this'" while attempting to update the React state using Redux saga. Could someone shed light on what's wrong with the code below and how I can fix it? class Welcome extends React.Component ...

Having trouble updating the DataTable with extra details retrieved from a new URL

I'm currently utilizing the DataTable plugin. After loading the DataTable, my aim is to reload the table, while keeping the existing content intact, and adding information gathered from a separate json file. However, I'm encountering an issue wh ...

Adding external JavaScript and jQuery files in Nuxt 3: A step-by-step guide

After successfully adding the CSS files in Nuxt 3 and nuxt.config.ts, everything is working as intended. The next step involves determining the ideal folder to add these script files. Any suggestions on the best approach to solve this issue? ...

The home navigation item's color remains active, even after changing the NavLink in ReactJs

When using NavLink for Routing and showing the active item of selected items, I am facing an issue where the home item is always shown as active even when switching to other items. This problem does not occur with items other than home. Can someone help m ...

Incorporating basic routing in Express.js from within the index.js script

I have a task to create 2 pages using 2 jade files. However, I am encountering an issue with the following code: exports.index = function(req, res){ res.render('index', { title: 'Welcome' }); }; exports.room = function(req, res){ ...

Enhance and soften images using CSS with smooth responsiveness across all web browsers

When an image is clicked, it should zoom in and become the background of the page with a blurred effect. I attempted to achieve this using the following code... <style type="text/css"> body{ position: absolute; margin-left: 100px; right: 0; z-inde ...

html and css code to create a linebreak ↵

I received a JSON response from the server, and within this data is a "return line" in the text. {text: "I appear in the first line ↵ and I appear in the second line"} However, when I try to display this on an HTML page, the "return line" does not show ...

React Material UI - All radio buttons within a list can be individually selected

I'm looking to create a set of Radio Buttons for each element in my array. While my project is functioning well overall, I'm having issues with the radio buttons as they are all selectable at once. ...

What steps are involved in setting up a dropdown side navbar?

Is there a way to automatically activate the next dropdown in the side navbar when I click on the 'Next' button? And similarly, can we open the previous dropdown in the side navbar when clicking the 'Previous' button? ...