How to put checks on pattern in Express?
I have a url:
http://localhost:3030/total?id=1234#12
I get the complete url by req.url which contains:
/total?id=1234#12
Is there any string pattern match syntax in Express, like I would like to separate the /total?id= part.
It looks like you're looking for req.query. That will give you an object based on the keys and values in your query string.
You can use both req.path and req.query to separate /total?id=1234#12.
req.path will give you "/total"
req.query.id will give you "1234#12"
Related
Here is below my code of route:-
app.get('/server/lead/get/:id?', leadCtrl.get);
app.get('/server/lead/filter/:filterQuery', leadCtrl.get);
As you see above i am using different route to access same controller method leadCtrl.get.
Now, i want something like route app.get('/server/lead/get/:id?:filter?', leadCtrl.get);. So, i can get params either req.params.id or req.params.filter but only one at a time.
What you asked in the question is not possible in the form that you describe it.
Now, i want something like route
app.get('/server/lead/get/:id?:filter?', leadCtrl.get);. So, i can get
params either req.params.id or req.params.filter but only one at a
time.
Your router would have no way to differentiate those two parameters. If it got a request to /server/lead/get/X then what is X? A filter or an ID?
Your options
You have few solutions here:
You can either keep using two routes like you did before.
You can use a common parameter for both cases as Robert explained in the comments.
Or you can use what seems to me the perfect solution for your use case - named query parameters - just use a route /server/lead/get and use query parameters to pass id and the filter.
Example URLs:
/server/lead/get?id=xxx
/server/lead/get?filterQuery=xxx
You will only have to make sure in your handler that only one of those two are set at a time with something like:
if (req.query.id && req.query.filterQuery) {
// respond with error
}
You can even mix the two if you have app.get('/server/lead/get/:id?') route you can have the id in the route and filterQuery as a query parameter. Now the URLs would be:
/server/lead/get/xxx (for id)
/server/lead/get?filterQuery=xxx (for filter)
For more info see: http://expressjs.com/en/api.html#req.query
Better way
If you follow some REST conventions then you can use:
app.get('/server/lead/:id') for one object with id (not optional)
app.get('/server/lead') for a list of objects (with optional filterQuery passed as a query parameter)
That way you would always know that when you access:
/server/lead/xxx - then it's one object with ID = xxx
/server/lead - then it's a list of any objects
/server/lead?filterQuery=xxx - then it's a list of objects that match the query
If you follow the REST conventions for things like this instead of inventing your own, it would be much easier for you to design the routes and handlers, and it would be much easier for other people to use your system.
You may also want to use plural /server/leads instead of /server/lead which is common with REST. That way it will be more obvious that leads is a list and leads/id is one of its elements.
For more info see:
https://en.wikipedia.org/wiki/Representational_state_transfer
http://www.restapitutorial.com/lessons/whatisrest.html
https://spring.io/understanding/REST
You have to realize that the following two routes match exactly the same:
app.get('/server/lead/get/:id?', leadCtrl.get);
app.get('/server/lead/get/:filter?', leadCtrl.get);
Express doesn't care about how you name the placeholders, so any requests for /server/lead/get/SOMEVALUE will always match the first (the one with :id).
You can add a distinction yourself, by only allowing a parameter to match a particular regular expression. From your code, it looks like :id should match MongoDB ObjectId's, so you can create a specific match for those:
app.get('/server/lead/get/:id([a-fA-F0-9]{24})?', leadCtrl.get);
If SOMEVALUE matches an ObjectId, it will call leadCtrl.get and populate req.params.id. If you also add another router for "the rest", you can also cover the req.params.filter case:
app.get('/server/lead/get/:filter?', leadCtrl.get);
As an aside: you're saying that you're passing JSON to the "filter" routes, in the URL. I would strongly suggest using a POST route for that, and post the JSON as request body content.
When using body-parser in node.js, I want the send keys be case insensitive. suppose that we send a json such as { "Name" : "Dariush" } and I want to get 'Name' value, in two ways:
request.body.name
&
request.body.Name
But by default, just request.body.Name works! and I want the 'request.body.name' works too.
Pre-process request.body keys with a lower case function and use only request.body.name.
Please, follow the answer https://stackoverflow.com/a/17945574/84661
There is also an express.js middleware for a related purpose: https://www.npmjs.com/package/express-uncapitalize
How do I made path a like api.get('/view/:search/:userid', search) work with /view//12, giving params.search an empty value?
Can you please try the following:
api.get('/view/:search?/:userid', search)
or if you define a new route
api.get('/view//:userid', search)
Main differences between req.query and req.param in Express
How are Both different from each other
When to use then in what cases
Suppose a client sends say Android (Key,value) pair in the request ........ which one to use ?
[EDIT]
Suppose android sends a POST request -> Intention is to send (Key,Value) to client and the server should perform a database query based on the value in the server and return JSON response
Look:: at this question for the program i referenced:: Simple Express program for querying a result
req.query will return a JS object after the query string is parsed.
/user?name=tom&age=55 - req.query would yield {name:"tom", age: "55"}
req.params will return parameters in the matched route.
If your route is /user/:id and you make a request to /user/5 - req.params would yield {id: "5"}
req.param is a function that peels parameters out of the request. All of this can be found here.
UPDATE
If the verb is a POST and you are using bodyParser, then you should be able to get the form body in you function with req.body. That will be the parsed JS version of the POSTed form.
req.query is the query string sent to the server, example /page?test=1, req.param is the parameters passed to the handler.
app.get('/user/:id', handler);, going to /user/blah, req.param.id would return blah;
I would suggest using following
req.param('<param_name>')
req.param("") works as following
Lookup is performed in the following order:
req.params
req.body
req.query
Direct access to req.body, req.params, and req.query should be favoured for clarity - unless you truly accept input from each object.
Ref:http://expressjs.com/4x/api.html#req.param
Passing params
GET request to "/cars/honda"
returns a list of Honda car models
Passing query
GET request to "/car/honda?color=blue"
returns a list of Honda car models,
but filtered so only models with an stock color of blue are returned.
It doesn't make sense to add those filters into the URL parameters (/car/honda/color/blue) because according to REST, that would imply that we want to get a bunch of information about the color "blue". Since what we really want is a filtered list of Honda models, we use query strings to filter down the results that get returned.
Notice that the query strings are really just { key: value } pairs in a slightly different format: ?key1=value1&key2=value2&key3=value3.
I have created a search form with get method. But when the url looks like this search.php?search[] or search?search[] (mod_rewrite) then I get a sql fattal error. It's passing an array and I want to avoid that problem.
my question is how do I redirect a person from that url to search.php
It sounds like you are directly passing the ?search[] query string variable into your SQL. mod_rewrite won't fix this for you... what if I decide to call your page with http://www.yoursite.com/search.php?search=;DROP TABLE users;? You simply aren't able to use mod_rewrite to predict all the bad kinds of input that a user can come up with.
Your code needs to be doing input validation and sanitization. You must assume that everything your script receives from the user is malicious and dangerous. That includes all data inside $_GET, $_POST and $_COOKIE.
The right solution here is to check that $_GET['search'] is a valid value to be passing to your SQL. Something like:
if (is_string($_GET['search']) && ! empty($_GET['search']) {
//escape the input properly using your database-specific method, e.g.:
$searchParam = mysql_real_escape_string($_GET['search']);
//run your query with the escaped data
}
At a minimum, that would ensure that your passed in search variable was not an empty string.