Node.js:从请求中获取路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18931452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:42:39  来源:igfitidea点击:

Node.js: get path from the request

javascriptnode.jsexpress

提问by Nabil Djarallah

I have a service called "localhost:3000/returnStat" that should take a file path as parameter. For example '/BackupFolder/toto/tata/titi/myfile.txt'.

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

How can I test this service on my browser? How can I format this request using Express for instance?

如何在我的浏览器上测试此服务?例如,如何使用 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);
});
};

回答by Gaurav

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.');

I have not tested your code but other things works

我还没有测试过你的代码,但其他事情有效

If you want to get the path info from request url

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

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

1.If you are getting the URL parameters still not able to read the file just correct your file path in my example. If you place index.html in same directory as server code it would work...

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

2.if you have big folder structure that you want to host using node then I would advise you to use some framework like expressjs

2.如果您想使用 node 托管大文件夹结构,那么我建议您使用诸如 expressjs 之类的框架

If you want raw solution to file path

如果您想要文件路径的原始解决方案

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;

source : http://www.nodebeginner.org/

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

回答by Sagiv Ofek

simply call req.url. that should do the work. you'll get something like /something?bla=foo

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

回答by kumbhani bhavesh

You can use this in app.jsfile .

您可以在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);

回答by Xin

req.protocol + '://' + req.get('host') + req.originalUrl

or

或者

req.protocol + '://' + req.headers.host + req.originalUrl// I like this one as it survives from proxy server, getting the original host name

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

回答by Ideabile

Based on @epegzz suggestion for the regex.

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

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

returns an array with paths.

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

回答by loretoparisi

Combining solutions above when using express request:

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

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

this will handle all cases like

这将处理所有情况,例如

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

etc. Some examples:

等一些例子:

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