gpt4 book ai didi

node.js - res 不在范围内吗? ( Node .js)

转载 作者:太空宇宙 更新时间:2023-11-03 22:44:43 25 4
gpt4 key购买 nike

var http = require('http');
var url= require('url');
var util= require('util');
var fs = require('fs');

var body_404="<html><body><center>404 error</center></body></html>";

http.createServer(function (req,res) {
var what = url.parse("http://127.0.0.1:1235"+req.url);
var pathname = what.pathname;

switch(pathname) {
case "/":
pathname="/www/index.html";
default:
res.writeHead(200, {'Content-type' : 'text/html'});
ret = res;
fs.stat("."+pathname, function (err, stat) {
if(err)
res.write(body_404);
else
res.write(fs.readFileSync("."+pathname));
});
res.end();
break;
}
}).listen(1235, '127.0.0.1');

我想知道为什么 fs.stat 回调中的 write 方法实际上似乎没有向客户端写入任何内容。我相信 res 在范围内。

最佳答案

您在 res.write 之前调用 res.end。因此,什么也没有写出来。将对 res.end 的调用移至 stat 处理程序中:

var http = require('http');
var url= require('url');
var util= require('util');
var fs = require('fs');
var path = require('path');

var body_404="<html><body><center>404 error</center></body></html>";
var rootPath = path.abspath(".");

http.createServer(function (req,res) {
var what = url.parse("http://127.0.0.1:1235"+req.url);
var pathname = what.pathname;
var buffer;

switch(pathname) {
case "/":
pathname="/www/index.html";
default:
var filename = path.join(rootPath, pathname);
if (filename.indexOf(rootPath) !== 0) {
res.writeHead(400, {'Content-type': 'text/plain'});
res.write('Directory traversal attack averted.');
res.end();
return;
}
fs.readFile(function (err, content) {
if(err) {
res.writeHead(404, {'Content-type' : 'text/html'});
res.write(body_404);
} else {
res.writeHead(200, {'Content-type' : 'text/html'});
res.write(content);
}
res.end();
});
break;
}
}).listen(1235, '127.0.0.1');

另请注意,您的原始代码容易受到 directory traversal attacks 的攻击。 ,并且患有 race condition在 os.stat 和 os.readFileSync 之间。

关于node.js - res 不在范围内吗? ( Node .js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12343278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com