简体   繁体   中英

URL parameters before the domain

I have a question about routing and urls in general. My question regards parameters or queries in the url before the domain itself. For example:

http://param.example.com/

I ask this question because I am using ExpressJS and you only define your routes after the domain itself like:

http://example.com/yourRoute

Which would be added to the end of the url. What I want is to be able to store parameters inbefore the domain itself.

Thank you in advance!

FYI

I do know how to use parameters and queries, I just don't know how I would go about to insert them before the domain.

Maybe this vhost middleware is useful for your situation: https://github.com/expressjs/vhost#using-with-connect-for-user-subdomains

Otherwise a similar approach would work: create a middleware function that parses the url and stores the extracted value in an attribute of the request.

You can create an if statement which can look at the sub-domain through the express req.headers.host variable which contains the domain of the request. For example:

-- google.com/anything/another
req.headers.host => "google.com"

-- docs.google.com/anything/
req.headers.host => "docs.google.com"

So working off this in your route you can call Next() if the request doesn't match the form you want.

router.get('/', function(req, res, next) {
        if (req.headers.host == "sub.google.com") {
            //Code for res goes here
        } else {
            //Moves on to next route option b/c it didn't match
            next();
        }
    });

This can be expanded on a lot! Including the fact that many packages have been created to accomplish this (eg. subdomain ) Disclaimer you may need to account for the use of www. with some urls.

So I would use something like

router.get('/myRoute', function(req, res,next) {
  req.headers.host == ":param.localhost.com"
  //rest of code
}

I think I understand what you are saying, but I will do some testing and some further reading upon the headers of my request.

EDIT: Right now it seems like an unnecessary hassle to continue with this because I am also working with React-router at the moment. So for the time being I am just going to use my params after the /. I thank you for your time and your answers. Have a nice day!

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