我正在使用以下脚本在浏览器中显示html文件:
var sys = require("sys"),
http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs");
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname;
var filename = path.join(process.cwd(), uri);
path.exists(filename, function(exists) {
if (!exists) {
response.sendHeader(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.close();
return;
}
fs.readFile(filename, "binary", function(err, file) {
if (err) {
response.sendHeader(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.close();
return;
}
response.sendHeader(200);
response.write(file, "binary");
response.close();
});
});
}).listen(8080);
sys.puts("Server running at http://localhost:8080/");
但是当我尝试导航到http://localhost:8080/path/to/file
时,我收到了这个错误:
Object #<ServerResponse> has no method 'sendHeader'
(at line 16).
我正在使用node-v0.4.12
答案 0 :(得分:3)
在节点v0.4.12中没有方法sendHeader
但看起来方法response.writeHead(statusCode, [reasonPhrase], [headers])
具有相同的API,因此您可以尝试将sendHeader
替换为{{1} }}
请参阅:http://nodejs.org/docs/v0.4.12/api/http.html#http.ServerResponse
答案 1 :(得分:0)
最近阅读此内容的任何人都应该注意,响应对象现在使用response.end()而不是response.close()