【问题标题】:Node.js: get path from the requestNode.js:从请求中获取路径
【发布时间】:2013-09-26 17:00:13
【问题描述】:

我有一个名为“localhost:3000/returnStat”的服务,它应该将文件路径作为参数。例如'/BackupFolder/toto/tata/titi/myfile.txt'。

如何在我的浏览器上测试这项服务? 例如,如何使用 Express 格式化此请求?

exports.returnStat = function(req, res) {

var fs = require('fs');
var neededstats = [];
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);
});
};

【问题讨论】:

标签: javascript node.js express


【解决方案1】:
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.');

我没有测试过你的代码,但是其他的东西可以用

如果你想从请求url获取路径信息

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

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

2.如果你有很大的文件夹结构,你想使用 node 来托管,那么我建议你使用一些框架,比如 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/

【讨论】:

  • 我的代码有效,但是我怎样才能检索文件路径(req 参数,例如'/BackupFolder/toto/tata/titi/myfile.txt')
  • 注意,url.parse()new URL() 弃用,但如果你通过'/',则后者会失败 =/
【解决方案2】:

只需致电req.url。那应该做的工作。你会得到类似/something?bla=foo

【讨论】:

  • 您的示例中的路径是/something
  • 使用req.url.match('^[^?]*')[0] 只显示路径
  • 我觉得有一个不需要凌乱的正则表达式的内置函数
【解决方案3】:

您可以在app.js 文件中使用它。

var apiurl = express.Router();
apiurl.use(function(req, res, next) {
    var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
    next();
});
app.use('/', apiurl);

【讨论】:

  • 使用hostname 不是主机。
【解决方案4】:
req.protocol + '://' + req.get('host') + req.originalUrl

req.protocol + '://' + req.headers.host + req.originalUrl // 我喜欢这个,因为它从代理服务器中幸存下来,得到原始主机名

【讨论】:

  • 使用hostname 不是主机。
【解决方案5】:

基于@epegzz 对正则表达式的建议。

( url ) => {
  return url.match('^[^?]*')[0].split('/').slice(1)
}

返回一个带有路径的数组。

【讨论】:

    【解决方案6】:

    使用快速请求时结合上述解决方案:

    let url=url.parse(req.originalUrl);
    let page = url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '';
    

    这将处理所有情况,如

    localhost/page
    localhost:3000/page/
    /page?item_id=1
    localhost:3000/
    localhost/
    

    等等。一些例子:

    > urls
    [ 'http://localhost/page',
      'http://localhost:3000/page/',
      'http://localhost/page?item_id=1',
      'http://localhost/',
      'http://localhost:3000/',
      'http://localhost/',
      'http://localhost:3000/page#item_id=2',
      'http://localhost:3000/page?item_id=2#3',
      'http://localhost',
      'http://localhost:3000' ]
    > urls.map(uri => url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '' )
    [ 'page', 'page', 'page', '', '', '', 'page', 'page', '', '' ]
    

    【讨论】:

      【解决方案7】:

      利用URL WebAPI 的更现代的解决方案:

      (req, res) => {
        const { pathname } = new URL(req.url || '', `https://${req.headers.host}`)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-17
        • 1970-01-01
        相关资源
        最近更新 更多