我想在index.html
请求时加载http://localhost:4935/
,因此我的代码就像
const MODULES_DIR = '/usr/local/lib/node_modules/';
const APP_PORT = 4935;
var express = require(MODULES_DIR + 'express'),
app = express(),
http = require('http'),
server = http.createServer(app),
io = require(MODULES_DIR + 'socket.io').listen(server),
fs = require('fs'),
path = require('path');
server.listen(APP_PORT);
app.get('*', function (req, res) {
if (fs.existsSync(__dirname + req.route.params))
res.sendfile(__dirname + req.route.params);
if (req.route.params == '/')
res.sendfile(__dirname + '/index.html');
});
在此我得到错误:
web@web-X501A1 ~ $ node '/home/web/www/nodechat/server.js'
info - socket.io started
http.js:691
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:691:11)
at ServerResponse.res.setHeader (/usr/local/lib/node_modules/express/node_modules/connect/lib/patch.js:63:22)
at SendStream.type (/usr/local/lib/node_modules/express/node_modules/send/lib/send.js:456:7)
at SendStream.send (/usr/local/lib/node_modules/express/node_modules/send/lib/send.js:348:8)
at /usr/local/lib/node_modules/express/node_modules/send/lib/send.js:323:10
at Object.oncomplete (fs.js:107:15)
我从错误中了解问题是res.sendfile
只能发送一次......基本上我需要自动加载所有JS
和CSS
。
答案 0 :(得分:1)
而不是:
app.get('*', function (req, res) {
...
});
使用此:
app.use(express.static(__dirname));