How to access route parameters in node.JS? - 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

Related

how to fetch req.params whatever it was

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]

multiple requests in one URLusing expressJS

I am using Express with Node and I have a requirement in which the user can request the URL as: http://myhost/api/add?mid="mid01"/userID
and I tried this
app.get('/api/:myMedia/:id', function (req, res){
...
})
and tried these req.query for getting mid01 and it didn't work.
I want to have req.params.id and req.query together. How can I handle this?
If your requirement really is http://myhost/api/add?mid="mid01"/userID, it might be a good idea to change that requirement, because it seems really not the right way to do something
But if you really want to do that you should declare your route like app.get('/api/add', ...)
Then with req.query.mid you can get your query value which is "mid01"/userID
Finaly it's up to you to parse that query value to do what you want
But you should not use URL like that, if possible try to use URL in a more standard way, http://myhost/api/add/userID?mid=mid01 or http://myhost/api/add?mid=mid01&path=/userID
To chain requests, use &. http://myhost/api/add?foo1="bar1"&foo2="bar2". This way both of the queries will show up.

NodeJS defining param name of glob value in url

Hi there I'm defining my get as below:
app.get('/list/:productType/*', middleware.isAuthenticated, function (req, res) {
});
Using this I am able to get the value of productType by calling the req.params.productType. The question is, however. How to do get the rest of the URL defined by the * global rule in the same way that I'd grab the productType parameter.
Thanks for your help!
I don't think there is a direct way to achieve this, you have two options
1) you can be more specific in defining the route e.g. '/list/:productType/:version/' and access the parameter using req.params.version
2) you can use req.url property to get the full request url and manually parse path after /:productType.
I worked out the answer: When console logging req.params the object has the "wildcard" string in the root index of this object. Thanks guys!

ExpressJS sendFile() cannot send URL GET parameters

I'm new to Node.js and Express.js and its routing. It's all set up correctly and it all works except for the following code.
I tried the following code:
app.get("/game/*", function(req, res) {
res.sendFile(__dirname + "/public/game.html?gameId=" + /\/([^\/]+$)/.exec(req.url)[1]);
});
The goal was to send all requests with /game/{gameId} (where gameId is some number) to /public/game.html?gameId={gameId}.
It correctly gets the requests with /game/, gets the gameId parameter from the URL, and attempts to sendFile() it. However, the sendFile() does not work, saying:
web.1 | Error: ENOENT, stat '/opt/lampp/htdocs/papei/public/game/32'
I've searched this error, and I guess it has to do with a file not being found. The problem is, /public/game.html exists. If I remove the ?gameId... part in the sendFile(), then it works. But I guess the sendFile() is looking for an exact URL, and is not finding it.
Is there any way to send URL GET parameters using ExpressJS?
I think the problem is that sendFile tries to find an exact match (which your query parameters break) as you thought.
You could use express-static to serve the html page, and then redirect to it as needed like so:
app.get("/game/:gameid", function(req, res) {
// Not ideal, as it uses two requests
res.redirect('/game.html?gameId=' + req.params.gameid)
});
Or you could put the html inside a template and render it for the response e.g:
app.get("/game/:gameid", function(req, res) {
// Render the 'game' template and pass in the gameid to the template
res.render('game', {gameid: req.params.gameid})
});
Either way, you don't need to use a catch all route and regex to get query parameters, see req.params or req.query in the express documentation.
Hope this helps.

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!

Resources