gpt4 book ai didi

javascript - 从nodejs中的请求路由获取其余路径

转载 作者:搜寻专家 更新时间:2023-10-31 23:13:13 24 4
gpt4 key购买 nike

你能使用 express 从 reuqested 路由中获取 node.js 中的其余路径吗?

假设我的服务器在端口 8080 上,我只是访问 http://example.com:8080/get/path/to/file

var url = require("url");
app.get("/get/*", function(req, res) {
console.log(req.path);

// this will return
// '/get/path/to/file'

console.log(url.parse(req.path);

// this will return
// protocol: null,
// slashes: null,
// auth: null,
// host: null,
// port: null,
// hostname: null,
// hash: null,
// search: null,
// query: null,
// pathname: '/get/path/to/file',
// path: '/get/path/to/file',
// href: '/get/path/to/file' }
});

我在这里想要的是返回 path/to/file 有没有办法得到它?还是我的 app.get() 路由在这里错了?

我知道有很多方法可以使用 regexsplitsubstring 和许多其他使用普通 JavaScript 的方法,但我只想了解实现此目的的最佳方法。

最佳答案

您可以在 req.params 中找到 path/to/file :

When a regular expression is used for the route definition, capture groups are provided in the array using req.params[N], where N is the nth capture group. This rule is applied to unnamed wild-card matches with string routes such as /file/*:

// GET /get/path/to/file
req.params[0]
// => path/to/file

关于javascript - 从nodejs中的请求路由获取其余路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23876045/

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