简体   繁体   English

在 node.js 中为 HTTP GET 中的 URL 参数设置默认值

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

I am using node.js restify.我正在使用 node.js restify。

I have a HTTP GET request that looks like this;我有一个像这样的 HTTP GET 请求;

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;在我的处理函数中,要检索URL参数,相关代码是这样的;

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 GET 函数怎么办

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

The ZZZ parameter is not provided in the URL. URL 中未提供ZZZ参数。 How do I modify the code such that ZZZ will use a default value of, say, 111 ?如何修改代码,使ZZZ使用默认值,例如111

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.但是... GET 参数是查询字符串,所以我们可能想确保它是一个数字。

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 .因此,您可能需要'111'而不是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.此外,您可以parseInt所有查询字符串或toString如果它们都是数字,只需确保它们都保持相同的预期类型。 Unless of course these are all strings of text, in which case ignore all 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 || <YOUR DEFAULT VALUE>;

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

    app.get(url_path, respond);
} 

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 || req.query.limit || 0 0

This line check if the content was sent, if not, put 0 as default value此行检查内容是否已发送,如果未发送,则将 0 作为默认值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM