how to fetch req.params whatever it was - node.js

I'm working on a url shortener api. The problem i'm facing is that if I pass a parameter like https://www.youtube.com/watch?v=8aGhZQkoFbQ then req.params.url will only be equal to https://www.youtube.com/watch. I've looked a lot on stackoverflow and all the answers are similar but not what I'm looking for.
I want to parse the url parameter and get the characters it contains.
This is the URI i'm using right now
router.route('/add/:url(*)')

You can try something like this:
app.get(/[/]add[/].*/, function (req, res) {
var uri = req.originalUrl.replace(/^[/][^/]*[/]*/, '');
console.log(uri);
res.end();
});

Maybe you're wanting the query part of the URL? Take a look at req.query docs (and other parts of the request) and read about the parts of the URI or more formal definitions on wikipedia. Having the correct names will help you understand the Express.js docs.
From express.js docs:
// GET /search?q=tobi+ferret
req.query.q
// => "tobi ferret"
From wikipedia:
scheme:[//[user:password#]host[:port]][/]path[?query][#fragment]

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

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.

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.
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!

REST method GET for searching by criteria as json fro mongodb

I have an nodejs server with express and mongoose and I'd like to use method GET for search accoring to criteria which I'd like to provide as JSON object does anyone can help me how to implement it?
Or maybe should I use POST or PUT to make it?
http://hostname/modelname?criteria1=1&criteria2=2
router.route('/modelname')
.get(function (req, res, next) {
req.query.criteria1 === 1 // true
req.query.criteria2 === 2 // true
});
If you are unsure of what HTTP VERB you'd want to use,
POST - is primarily used for creating resources on the server
PUT - is used to update an existing resource
GET- to retrieve a resource
I would use GET in this case
GET http://myhost.com?q=word1+word2+word3+word4
app.get('*', function(req, res) {
// do something with the req.query.q array
});
You've got two options - using HTTP GET params or encoding whole criteria as JSON string and passing that string.
First option, by using params:
?crit[foo.bar][$eq]=abc&crit[foo.baz][$ne]=def
You can read it in nodejs/express via req.query.crit. But this is bad idea because there's no way of retaining data types. For example number 1 becomes string "1". Don't use it - MongoDB is data type sensitive so query {"foo.bar":{$eq:1}} is completely different from {"foo.bar":{$eq:"1"}}
Second option is to urlencode JSON criteria:
?critJSON=%7B%22foo.bar%22%3A%7B%22%24eq%22%3A%20%22abc%22%7D%2C%22foo.baz%22%3A%7B%22%24ne%22%3A%20%22def%22%7D%7D
And parse it on nodejs/express side:
var crit = JSON.parse(req.query.critJSON)
This way your data types are retained and it will work as expected.

Safe to append to req parameter?

In express, when I use routing middleware, is it OK to append to the request object? Or is it a bad pattern? Alternatives? Thanks.
app.get('/', getLayout, function(req, res){
if(req.layout == 'simple') ...render simple layout...
else ...render full layout...
});
where
getLayout = function(req, res, next){
req.layout = (req.params.blah == 'blah') ? 'layout_simple' : 'layout_full';
next();
}
I don't see why you shouldn't.
I do it a lot.
I am under the impression this is what middleware typically does.
From the express docs:
http://expressjs.com/guide.html#route-middleware
They set req.user in their middleware as the current user.
I agree with j_mcnally that this is a fine pattern as long as you don't go overboard. Specifically, I append most things that are more closely related to the response to the res object. This would be things like layout info, HTML fragments, my intermediate jsdom env representation of the response, etc. For req, tacking on things that are representations of query string or request body info makes sense. This would be things like input parameters, parsed search queries, the current user object, etc.
The express docs suggest it's somewhat a standard practice:
http://expressjs.com/guide.html#route-middleware
But it can significantly effect performance because of the way V8 works:
http://blog.tojicode.com/2012/03/javascript-memory-optimization-and.html
http://www.scirra.com/blog/76/how-to-write-low-garbage-real-time-javascript

Resources