具有对象类型的参数,其属性名称/值各不相同.需要在GET请求中通过URL发送道具名称/值

Have an argument of type object, whose property names/values vary. Need to send prop name/values through URL in GET request

本文关键字:请求 GET URL 属性 类型 对象 各不相同 参数      更新时间:2023-09-26

我的express api上有一个路由,它用Sequelize查询数据库,如下所示:

Islands.findAll({
    where: {
        region: 'pacific'
},
    include: {
        model: BonoboIslands,
        include: [ Bonobos ]
    }
}).then(function(result){
    res.send(result);
});

现在,where子句将根据用户的规格进行更改——它可能像这里的太平洋一样通用,也可能用户对某个特定的岛屿感兴趣,因此where子句将反映这一点。在这种情况下,它将是where: { island: 'cliffburger' }

我想通过像/bonoboLibrary/:locationParam/:locationValue这样的url传递这些信息,但当我从req.params.locationParamreq.params.locationValue获得对象时,我如何对其进行编码,从而得到这样的对象:{ locationParam : "locationValue" }

在javascript中,可以使用数组表示法创建具有动态名称的对象属性:

var whereClause = {};
whereClause[req.params.locationParam] = req.params.locationValue;
// for /bonoboLibrary/island/cliffburger
// whereClause is { island: 'cliffburger' }
Islands.findAll({
    where: whereClause,
    // ....
});