简体   繁体   中英

Extract URL from a server in Node.js

I'm making a Node.js server and I need to extract one part from a URL with this structure:

https://lets-talk-saku-gie-sakura.c9users.io/sala?extract

I just need the extract part.

I need to use the app.get method. However, the only way that I've found is:

app.get('/sala/:id', function (req, res) {
    req.params.id;
});

This doesn't work; do you know how can I extract it?

req.params is for URL parameters like :id . Since you want a query parameter you should use req.query instead.

app.get('/sala/:id', function (req, res) {
  console.log(req.query);
});

req.query might seem like a way to do this but, unfortunately, it's only useful when you know or expect certain query strings. Your best bet, I think, is to use req.originalUrl and then use a regular expression to find the part of the url you want to extract. See http://expressjs.com/en/4x/api.html#req.originalUrl

The nodejs HTTP doc has an example that can help you:

var obj = require('url').parse(req.url);
console.log(obj.query); // output: extract

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM