本文介绍了Express.js sendFile返回ECONNABORTED的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在运行Express.js(3.8.6)的简单节点服务器上.我正在尝试使用sendFile
将简单的HTML文件发送到客户端.
On a simple node server running Express.js (3.8.6). I am attempting to use sendFile
to send a simple HTML file to the client.
- 从读取的文件来看,该路径是正确的.
- 浏览器上的缓存已禁用.
- 显示的代码是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();
});
项目设置
推荐答案
您正在过早调用res.end()
.请记住,Node.js是异步的,因此您实际上正在做的是在sendFile
完成之前将其取消.将其更改为:
You're prematurely calling res.end()
. Remember, that Node.js is asynchronous, thus what you're actually doing is cancelling your sendFile
before it completes. Change it to :
app.get('/', function(req, res){
res.sendFile(myPath, null, function(err){
console.log(err);
res.end();
});
});
这篇关于Express.js sendFile返回ECONNABORTED的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!