Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs - TypeError: Cannot read property 'headersSent' of undefined

I'm trying to build a simple chat using nodejs, express and socket.io. But when i run my app, I receive an erro in finalhandler. But I don't even know what this is. Google did not help this time

All I got was some github discussions, nothing that really helps me

What is finalhandler? I even tried to restart my project, only with socketio and server and I got the same error

app.js:

var express = require("express")();
var http = require("http").Server(app);
var io = require("socket.io")(http);
var path = require("path");

var app = express();
var clients = {};

app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res){
    res.render('index');
});

io.on("connection", function(client) {
    console.log('user connected');
});

io.on("connection", function(client) {
    client.on("join", function(name){
        console.log("Joined: " + name);
        clients[client.id] = name;
        client.emit("update", "Você está conectado ao servidor");
        client.broadcast.emit("Update! => ", name + "entrou no servidor");
    });
    client.on("send", function(msg){
        console.log("Mensagem: " + msg);
        client.broadcast.emit("chat", clients[client.id], msg); 
    });
    client.on("disconnect", function(){
        console.log("Disconectado");
        io.emmit("Update! => ", clients[client.id] + " saiu do servidor");
        delete clients[client.id];
    });
});

http.listen(3000, function(){
    console.log('Rodando na porta 3000');
});

package.json:

{
  "name": "diga",
  "version": "1.0.0",
  "description": "",
  "main": "nodemon",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "serve": "nodemon app.js"
  },
  "repository": {
    "type": "git",
    "url": ""
  },
  "author": "juliana",
  "license": "ISC",
  "dependencies": {
    "@types/socket.io": "^1.4.36",
    "ejs": "^2.6.1",
    "express": "^4.16.3",
    "g": "^2.0.1",
    "jquery": "^3.3.1",
    "socket.io-client": "^2.1.1",
    "socketio": "^1.0.0"
  },
  "devDependencies": {
    "nodemon": "^1.17.5"
  }
}

enter image description here

like image 524
nanquim Avatar asked Jul 25 '26 11:07

nanquim


1 Answers

Follow this, it will help you You have used express like

var express = require("express")();

kindly replace it from:

var express = require('express')

like image 177
radhey shyam Avatar answered Jul 27 '26 03:07

radhey shyam