在节点MVC中传递req.params

时间:2018-07-04 10:52:57

标签: javascript node.js express model-view-controller

我试图弄清楚如何在MVC上下文中使用Express传递req.params。

我知道如何正确引用req.params,但是当我将app.js拆分为模型和控制器时,我很迷茫。

参考代码:

routes.js

app.get('/category/:category', descriptor.getSingleCategory)

model.js

let getSingleCat = (cb) => {
    let queryString = 'SELECT * FROM categories WHERE category_id = $1'
    let queryValue = [req.params.category]
    db.query(queryString, queryValue, cb)
}

controller.js

const getSingleCategory = (req, response) => {
    console.log(req.params.category);
    db.desc.getSingleCat((err, queryRes) => {
        if (err) {
            //render something went wrong
            response.send('something went wrong')
        } else {
            response.send(queryRes.rows)
        }
    })
}

我已经检查了所有需求,并且它们工作正常。是否有不使用中间件就传递req.params的有效方法?

1 个答案:

答案 0 :(得分:2)

在模型中使用req.params的唯一方法是将其作为参数发送,如下例所示:

model.js

let getSingleCat = (params, cb) => {
    let queryString = 'SELECT * FROM categories WHERE category_id = $1'
    let queryValue = params.category
    db.query(queryString, queryValue, cb)
}

controller.js

const getSingleCategory = (req, response) => {
    console.log(req.params.category);
    db.desc.getSingleCat(req.params, (err, queryRes) => {
        if (err) {
            //render something went wrong
            response.send('something went wrong')
        } else {
            response.send(queryRes.rows)
        }
    })
}

您不能使用全局变量,因此这是唯一的方法。另外,只能在绑定到将接收实际请求的端点的函数中访问此变量(req)。