Express.js的sendFile返回ECONNABORTED错误

8
在运行 Express.js(3.8.6)的简单节点服务器上,我试图使用 sendFile 将一个简单的 HTML 文件发送给客户端。
  • 从读取文件中显示的路径是正确的。
  • 浏览器上的缓存已禁用。
  • 所显示的代码是 server.js 文件,直接从节点运行。
我错过了什么? 代码
//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();
});

项目设置

项目设置

2个回答

10

你过早地调用了 res.end()。要记住,Node.js是异步的,因此实际上你正在取消sendFile在完成之前。请将其更改为:

app.get('/', function(req, res){
  res.sendFile(myPath, null, function(err){
    console.log(err);
    res.end();
  });
});

谢谢,我也遇到了同样的问题,我猜是因为我需要改进我的回调(异步)思路。 - Héctor J. Orihuela Ruiz

0

我之前下载(文件)也遇到了同样的问题,现在已经完美解决了。

 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();

        }
    })
});

1
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接