节点.js:从请求中获取路径

Node.js: get path from the request

本文关键字:获取 路径 请求 js 节点      更新时间:2023-09-26

我有一个名为"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);
});
};
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参数仍然无法读取文件,只需在我的示例中更正文件路径即可。如果你把索引.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.url。 这应该可以完成工作。 你会得到类似/something?bla=foo

您可以在

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);
利用

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

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

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

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

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

返回一个包含路径的数组。

我用过这个const { pathname } = req?._parsedUrl || {};,它对我有用

使用明示请求时组合上述解决方案:

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', '', '' ]