首页 > 解决方案 > 使用 socket.io 发送标头后无法设置标头

问题描述

我是 nodeJs 的新手。我正在使用icket.io 收到此错误“发送后无法设置标头”

这是我的代码

 var app = require('express')();
var http = require('http').createServer(app);

app.get('/', (req, res) => {
  res.send('<h1>Hello world</h1>');
  res.sendFile(__dirname + '/socket.html');
});

http.listen(3000, () => {
  console.log('listening on *:3000');
});

这是我的 html 文件

<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: 0.5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
  </body>
</html>

标签: node.jsexpresssocket.io

解决方案


你要么打电话,res.send要么res.sendFile不打电话:

app.get('/', (req, res) => {
  res.send('<h1>Hello world</h1>');
});

或者

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/socket.html');
});

推荐阅读