您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Node.js:从请求获取路径

Node.js:从请求获取路径

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

var neededstats = [];

http.createServer(function(req, res) {
    if (req.url == '/index.html' || req.url == '/') {
        fs.readFile('./index.html', function(err, data) {
            res.end(data);
        });
    } else {
        var p = __dirname + '/' + req.params.filepath;
        fs.stat(p, function(err, stats) {
            if (err) {
                throw err;
            }
            neededstats.push(stats.mtime);
            neededstats.push(stats.size);
            res.send(neededstats);
        });
    }
}).listen(8080, '0.0.0.0');
console.log('Server running.');

我尚未测试您的代码,但其他方法可行

 var url_parts = url.parse(req.url);
 console.log(url_parts);
 console.log(url_parts.pathname);

1.如果您获取的URL参数仍然无法读取文件,请在我的示例中更正您的文件路径。如果将index.html与服务器代码放在同一目录中,它将起作用…

2.如果您要使用节点托管大型文件夹结构,则建议您使用expressjs等框架

var http = require("http");
var url = require("url");

function start() {
function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
}

http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}

exports.start = start;

来源:http ://www.nodebeginner.org/

Node 2022/1/1 18:22:10 有348人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶