在运行Express(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();
});
Run Code Online (Sandbox Code Playgroud)
项目设置
您正在提早打电话res.end()。请记住,Node.js是异步的,因此您实际要做的是sendFile在完成之前先取消它。将其更改为:
app.get('/', function(req, res){
res.sendFile(myPath, null, function(err){
console.log(err);
res.end();
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2897 次 |
| 最近记录: |