【问题标题】:Create a REST API in nodejs在 nodejs 中创建一个 REST API
【发布时间】:2018-06-19 05:45:50
【问题描述】:

我有一个 postgresql 表,看起来像:

man_id subgroup power group
1 sub_A 1 Group_A
2 Sub_B -1 Group_A
3 Sub_A -1 Group_B
4 Sub_B 1 Group_B
5 Sub_A -1 Group_A
6 Sub_B 1 Group_A
7 Sub_A -1 Group_B
8 Sub_B 1 Group_B

我们在这里有一个功率计算,它的工作原理是,

Total Power of Subgroup Sub_A in the Group Group_A is (1 + (-1) ) = 0
Total Power of Subgroup Sub_B in the Group Group_A is ((-1) + 1 ) = 0
Total Power of Subgroup Sub_A in the Group Group_B is ((-1) + (-1) ) = -2
Total Power of Subgroup Sub_B in the Group Group_B is (1 + 1 ) = 2

So the power of `Sub_A` in the Group_A is not equal to power of Sub_A in the Group_B
So the power of Sub_B in the Group_A is not equal to power of Sub_B in the Group_B

我想在 nodejs 中创建一个 REST API,我可以在其中使用子组名称进行查询。如果对于同一个子组名,所有其他组名的幂相等,则返回是,否则返回否。

举个例子,

http://localhost:3000/api/check/Sub_A 将返回 NO

http://localhost:3000/api/check/Sub_B 将返回 NO

我可以连接数据库并列出 JSON 中的所有条目。下面是我的代码,

http://localhost:3000/api/lists 将返回数据库中的所有条目。

查询.js

var promise = require('bluebird');

var options = {
  // Initialization Options
  promiseLib: promise
};

var pgp = require('pg-promise')(options);
var connectionString = 'postgres://localhost:5432/lists';
var db = pgp(connectionString);

// add query functions

module.exports = {
  getAllList: getAllList
};


function getAllList(req, res, next) {
  db.any('select * from dataset')
    .then(function (data) {
      res.status(200)
        .json({
          status: 'success',
          data: data,
          message: 'Retrieved ALL Data'
        });
    })
    .catch(function (err) {
      return next(err);
    });
}

index.js

var express = require('express');
var router = express.Router();

var db = require('../queries');


router.get('/api/lists', db.getAllList);



module.exports = router;

【问题讨论】:

    标签: javascript sql node.js postgresql


    【解决方案1】:

    您可以尝试使用 Express 请求对象中的 req.params 对象

    http://localhost:3000/api/check/{Subgroup}
    

    以下代码可能对您有所帮助

    app.get('/api/check/:subgroup?', (req, res) => {
      const subgroup = req.params.subgroup;
      res.json(...);
    });

    【讨论】:

    • 实际上,我正在寻找这个,如果对于同一个子组名称,所有其他组名称的功率相等,那么它将返回是,否则返回否。
    猜你喜欢
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 1970-01-01
    • 2015-10-15
    • 2021-10-26
    相关资源
    最近更新 更多