URL parameters before the domain - node.js

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.

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.

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.

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!

Related

How to access route parameters in node.JS?

I want to access the route parameters in Node.JS and I am using the following syntax:
app.get("posts/:postName", function(req,res){
console.log(req.params.postName)
});
Is something wrong in the syntax? The error I get in the browser is, "Cannot GET /posts/print". Over here, print was the key-word I chose.
If you're using Express (I think so for your syntax), you're doing it right:
http://expressjs.com/en/api.html#req
Could you paste more code or create an online example to see If you're instantiating correctly express?
Your code is missing /
app.get("/posts/:postName", function(req,res){
console.log(req.params.postName)
});
make sure you have one get rout if dont what to use "?" at the end this will make sure your this value of post name is in the rout or not and them put them in a sequence like
app.get("posts/:postName?", ( req, res ) => {})
as first rout is with no data in rout and rout below has data in rout with specific attribute
To access route parameter you have to use req.params.parameterName and access query string you have to use req.query.parameterName
Please modify your route like this -
app.get("/posts/:postName", function(req,res){
console.log(req.params.postName)
});
Suppose if you are trying to access page and limit from url like this http://example.com/**?page=2&limit=20**, then for page use req.query.page and for limit use req.query.limit

How to ignore specific files to be loaded when I use route parameters in Express

When I make a GET request with route parameters in express with mongoose like the following code, I sometimes see that the browser tries to load some unexpected files such as favicon.ico, robots.txt, humans.txt, sitemap.xml, ads.txt, etc., and 404 error shows up in the browser console.
app.get("/:userId", ...);
By refering to this Q&A, I figured out that if I don't use the route parameters right after the root route like the following code, it doesn't happen.
app.get("/user/:userId", ...);
In the same Q&A, however, there seem to be another way that uses req.url to ignore those unexpected files to be loaded, but it isn't explained in detail.
How do you do that?
All that's meant in that other answer is that you could examine req.url in your route handler and make sure it is not a known special name. In this specific case, it's probably simpler to use req.params.userId instead of req.url, but you could also use req.url in the same way.
const specials = new Set(["favicon.ico", "robots.txt", "humans.txt", "sitemap.xml", "ads.txt"]);
app.get("/:userId", (res, res, next) => {
// if it's a special URL, then skip it here
if (specials.has(req.params.userId)) {
next();
return;
}
// process your route here
});
Personally, I wouldn't recommend this solution because it presupposes a perfect knowledge of all possible special filenames. I don't use a top level wildcards ever because they ruin the ability to use your server for anything else.

Node.js route regex

i want a route url to be like this
http://localhost:3000/api/uploader/:path
The moment is that path can be '' => http://localhost:3000/uploader/ or string containing slashes like this aaa/bbb/ccc => http://localhost:3000/api/uploader/aaa/bbb/ccc
I wrote something like this for empty case
http://localhost:3000/api/uploader/:path?
How can I write regex for many slashes, so the req.params === /aaa/bbb/ccc ?
I'll assume you're using express and answer below.
What you're looking for is the * wildcard.
Try this and check it out:
router.get('/uploader/?*', function(req, res, next) {
res.send(req.originalUrl);
});
You should see the request url back to you so you can confirm.
Edit: I'm changing the wildcard with the question mark to accept baseUrl too***
Tell me if anything else, but that should do it. I hope this helps you out.

how to extract part of url server side in nodejs express

Currently working on a nodejs express server. And I think I'm doing something in an inefficient way. I have this route set up
app.get('/admin/scanTable/:table', require('./AUTH/ValidateCookie.js'), require('./AUTH/verifyURI.js'), require('./ROUTES/render.js'));
so the url here is /admin/scanTable/:table. I know I can get the whole path with req.route.path. I know I can use req.params.table to collect the table parameter. But the thing I don't know how to get is the first part of the path, in this case admin. I know I could get it by looking for / symbols and slicing the parts I need from req.route.path but I figure with all these functionalities that express has, there's probably a better way of doing this.
I know I can use
app.use('/admin', function(req, res, next){console.log('admin called'), next();});
to check if this part of the uri was called to then execute some code, but it's not really what I want. Can anyone tell me the easiest way to find this? At the moment I have attached a variable to req.string whenever app.use('/admin' is called it will attach the string admin to this variable which then makes it available to all other functions that are called. But even this feels like overkill. Any Ideas?
Both options you describe are valid and straightforward:
Using a regex on req.route.path, a la /^admin/.test(req.route.path)
Using middleware to attach a new property to the req object, a la
app.use('/admin', function(req, res, next){ req.adminRoute = true; next();});
or if you need to do this same thing for all admin routes, do it once:
var adminRouter = require("express").Router();
router.get("/scanTable/:table", require("./AUTH/ValidateCookie.js"), ...);
router.use(function (req, res, next) { req.adminRoute = true; next(); }));
app.use("/admin", adminRouter);
I don't know the context of your application, but I would consider using the last example, and putting anything else that's specific to /admin routes as middleware also.

How to get optional language parameter from URL in Express routes?

I'm stuck with a stupid problem:
How to work with optional locale parameter?
That's what I mean:
For example, I have frontpage and contacts, here is routes:
app.get('/', frontpage.get);
app.get('/contacts', contacts.get);
Now I'm trying to add localization to my site
app.all('/:lang?*', language.all); -> detect and set locale
app.get('/:lang?', frontpage.get);
app.get('/:lang?/contacts', contacts.get);
The only problem is when I don't use lang-parameter in URL:
mysite.com/contacts
because Express uses 'contacts' as a language parameter.
(+ I don't like this copy-pasted :lang?)
I think, I just took the wrong way.
How to use locale parameter from URL in Express?
PS: I dont want to use subdomains de.mysite.com or querystring mysite.com?lang=de. I want exactly this variant mysite.com/de
Most modules use Accept-Language so I can't find any that use the path like this that you might be able to use. So you'll need to define your own middleware that initializes before everything else. Express's Router doesn't really help for your usecase.
app.use(function(req, res, next){
var match = req.url.match(/^\/([A-Z]{2})([\/\?].*)?$/i);
if (match){
req.lang = match[1];
req.url = match[2] || '/';
}
next();
});
Now you can use req.lang in your routes or other middleware to configure your translation logic and since we have rewritten the URL, later logic will not know that there is a language param.

Resources