Set default value for URL parameter in HTTP GET in node.js

I am using node.js restify.

I have a HTTP GET request that looks like this;

http://127.0.0.1//read_val?XXX=123&YYY=456&ZZZ=789

In my handling function, to retrieve the URL parameters, the relevant code will be like this;

var api_get_func = function (app, url_path) {
    function respond(req, res, next) {
        var XXX= req.query.XXX;
        var YYY = req.query.YYY;
        var ZZZ = req.query.ZZZ;

        //SQL query ...
        return next();
    }

    app.get(url_path, respond);
} 

Now, what if I have a HTTP GET function like this below

http://127.0.0.1//read_val?XXX=123&YYY=456

The ZZZ parameter is not provided in the URL. How do I modify the code such that ZZZ will use a default value of, say, 111?

Answers:

Answer

If just want to check if something is provided, then you could just do:

var ZZZ = req.query.ZZZ || 111;

But... GET parameters are query strings, so we probably want to make sure it is a number.

if (!parseInt(req.query.ZZZ)) {
  req.query.ZZZ = 111;
}

Or if you want to get ternary with it:

req.query.ZZZ = parseInt(req.query.ZZZ) ? req.query.ZZZ : 111;

Do note that the other parameters are a string and that this default is being set as a number. So, you might want '111' as opposed to 111. Also, you can parseInt all of your query strings or toString them all if they are all a number, just try to make sure they all remain the same expected type. Unless of course these are all strings of text, in which case ignore all this.

Answer
var api_get_func = function (app, url_path) {
    function respond(req, res, next) {
        var XXX= req.query.XXX;
        var YYY = req.query.YYY;
        var ZZZ = req.query.ZZZ || <YOUR DEFAULT VALUE>;

        //SQL query ...
        return next();
    }`enter code here`

    app.get(url_path, respond);
} 
Answer

In one line, the best way is this:

let limit = parseInt(req.query.limit || 0);
let page = parseInt(req.query.pagina || 1);
let offset = page * limit

Because you put a default value then you parse the content.

req.query.limit || 0

This line check if the content was sent, if not, put 0 as default value

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.