在运行 Express.js (3.8.6) 的简单节点服务器上。我正在尝试使用sendFile
向客户端发送一个简单的 HTML 文件。
- 从读取的文件来看,该路径是正确的。
- 浏览器上的缓存已禁用。
- 显示的代码是 server.js 文件,直接从节点运行
我缺少什么?
Code
//server.js
var http = require("http");
var express = require("express");
var app = express();
var server = http.createServer(app);
var path = require('path');
//Server views folder as a static in case that's required for sendFile(??)
app.use('/views', express.static('views'));
var myPath = path.resolve("./views/lobbyView.html");
// File Testing
//--------------------------
//This works fine and dumps the file to my console window
var fs = require('fs');
fs.readFile(myPath, 'utf8', function (err,data) {
console.log (err ? err : data);
});
// Send File Testing
//--------------------------
//This writes nothing to the client and throws the ECONNABORTED error
app.get('/', function(req, res){
res.sendFile(myPath, null, function(err){
console.log(err);
});
res.end();
});
项目设置
你过早地打电话res.end()
。请记住,Node.js 是异步的,因此您实际上要做的是取消您的sendFile
在它完成之前。将其更改为:
app.get('/', function(req, res){
res.sendFile(myPath, null, function(err){
console.log(err);
res.end();
});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)