Reputation: 10453
Can you get the rest of the path in node.js from reuqested route using express?
Assuming I have my server on port 8080
and I just visit 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' }
});
What I want here is to return path/to/file
is there a way to get that? or could it be my app.get()
route is wrong here?
I know that there are ways to do it using regex
, split
, substring
and many other ways using plain JavaScript, but just want to see the best way to go for this.
Upvotes: 5
Views: 4295
Reputation: 763
I know this is a really old question, but I will post the answer for anyone searching for this. At the time of writing I am using express 4.18.2. To match the remainder of a route you can actually do something like this:
app.get("/some/url/:pathToFile(*)", (req, res) => {
const pathToFile = req.params["pathToFile"]; //<- Holds the remainder of the route.
});
So navigating to /some/url/path/to/file will result in the route above being matched and the pathToFile variable will be "path/to/file".
Upvotes: 1
Reputation: 39512
You can find path/to/file
in req.params
:
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
Upvotes: 5