Nodejs - TypeError:无法读取未定义的属性“headersSent”

enxuqcxy  于 2023-05-06  发布在  Node.js
关注(0)|答案(3)|浏览(105)

我正在尝试使用nodejs、express和socket.io建立一个简单的聊天。但是当我运行我的应用程序时,我在finalhandler中收到一个错误。但我都不知道这是什么。谷歌这次也没帮上忙
我得到的只是一些github上的讨论,没有什么真正对我有帮助的
什么是finalhandler?我甚至试图重新启动我的项目,只有与socketio和服务器和我得到了同样的错误
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"
  }
}

k3fezbri

k3fezbri1#

跟着这个,它会帮助你你用过express like

var express = require("express")();
请将其替换为:
var express = require('express')

umuewwlo

umuewwlo2#

如果你想得到更多的好处,不要先执行express,先执行express,如下所示:const express = require('express')
const app = express();
您将使用服务器引导应用程序,并使用express来帮助它提供静态文件,这些静态文件可以位于任何位置,例如。public如下

Now add all it will look as below

const express = require('express');
const app = express();

app.use(express.static('public'));

app.listen(3000, () => console.log('Its working on port 3000'))```
f3temu5u

f3temu5u3#

如果上面的例子不起作用,那就试试吧。

const express = require('express');
const app = Royexpress();

相关问题