简体   繁体   中英

NodeJs Express app.get that handles both query and params

I'm trying to create a REST Service. The route below will execute a stored procedure that will return json results

app.get('/spparam', function (req, res) {
var sql = require("mssql");

// config for your database
var id=0;
var config = {
    user: 'username',
    password: 'password',
    server: 'hostname', 
    database: 'databasename' 
};
// connect to your database
sql.connect(config, function (err) {

    if (err) console.log(err);

    // create Request object
    var request = new sql.Request();

    if(!mylib.isEmptyObject(req.query)){
        id=req.query.id;
    }else if(!mylib.isEmptyObject(req.params)){
        id=req.params["id"];
    }
    // Executing Stored Prcoedure       
    request.input('requestid', sql.Int, id)
        .execute("Request_Get_ById").then(function(recordSet) {
            //console.dir(recordsets);
            //console.dir(err);
            res.send(recordSet);
            sql.close();
        }).catch(function(err) {
            console.log(err);
        });
    });
});

I want to minimise my code by creating one route that will handle both query (/spparam?id=1) and params (/spparam/:id/). Is this possible? Is there a better way to handle what I need?

Yup, you can do that with Express like this:

app.get('/spparam/:id?', function (req, res) {
  const id = req.params.id || req.query.id;
  // the rest of your function, and use id without caring about whether
  // it came from params or query
  // change order if you want to give preference to query
}

The Express.js docs say it uses path-to-regexp for route matching purposes. There you can see this quote:

Parameters can be suffixed with a question mark (?) to make the parameter optional.

In javascript, the construct var a = b || c var a = b || c assigns the value of b to a if b is not false-y , and otherwise it assigns the value of c to a .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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