在运行Express.js的简单节点服务器上(3.8.6)。我试图使用sendFile向客户端发送一个简单的HTML文件。
我遗漏了什么?
码
//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();
});项目设置

发布于 2016-04-30 01:05:19
你过早地给res.end()打电话了。请记住,Node.js是异步的,因此实际上您要做的是在sendFile完成之前取消它。改为:
app.get('/', function(req, res){
res.sendFile(myPath, null, function(err){
console.log(err);
res.end();
});
});发布于 2022-03-22 01:21:07
我在下载(文件)方面也有同样的问题,现在它工作得很好。
server.get('/download', (req, res) => {
res.download('./text.txt', 'text.txt', function (err) {
if (err) {
res.status(404)
res.end();
console.log('download failed');
console.error(err);
} else {
console.log('downloaded seccefully');
res.end();
}
})
});https://stackoverflow.com/questions/36949557
复制相似问题