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

时间:2018-07-01 17:24:19

标签: node.js express socket.io

我正在尝试使用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"
  }
}

enter image description here

3 个答案:

答案 0 :(得分:1)

关注此问题,它将为您提供帮助 您曾经使用过

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

请将其替换为:

var express = require('express')

答案 1 :(得分:1)

如果您想获得更多好处,请不要先执行快递 首先获得快递,如下 const express = require('express')

从中取出服务器 const app = express();

您将使用服务器来引导应用程序并进行表达,以帮助其提供可位于任何位置的静态文件。公开如下


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'))```

答案 2 :(得分:0)

如果上述情况不起作用,请尝试。

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