NodeJS Express - 如何为 POST 请求创建配置文件?

NodeJS Express - How to Create Configuration File for POST Request?

我在 NodeJS 中使用 Express 接受 URL POST Request Call 然后系统将根据请求响应 JSON File。我当前的实现是在 Hardcode 方法中,因为每当我想添加更多 POST Request Input 并定义要读取的 JSON File 时,我都需要手动添加更多code 比如 if-else 中的语句 Javascript File.

我的期望输出:

是否可以使用 JSON 或 YAML 创建配置文件,允许用户在想要添加更多 Post Request Input 并添加更多条件时编辑配置文件 [= =14=] 打开而不是手动添加更多代码到 Javascript File?

我的动机是让用户可以轻松修改,而无需触及 Javascript File 本身的实现代码,但他们只需要处理配置文件即可。

硬编码方法:(已更新)

const postConfig = require( "./config/postConfig" )

// before allow configuration, the code is
// app.post('/api',function (req, res, next)
// after configuration, I just need to change the value in postConfig.json to determine the POST URL.
app.post(postConfig.URL,function (req, res, next) {

    // HARDCODE AREA - The POST Request Input
    // What I want is make this 'userID' is configurable/changable using JSON file. 
    // Which mean its value will based on the value at JSON file. But not HARDCODE it as 'userID'. 
    // If I want to change to 'foodID', I just change it at JSON file.
    var input = req.body.userID,


  // HARDCODE AREA - ALL OF THE IF ELSE Statement
  if(input =="1"){

    var contents = fs.readFileSync(publicdir+"/api/a.json");
    var jsonContent = JSON.parse(contents);
    res.send(jsonContent);

  }else if(input =="2"){

    var contents = fs.readFileSync(publicdir+"/api/b.json");
    var jsonContent = JSON.parse(contents);
    res.send(jsonContent);

  }else{
    res.status(404);
    res.json({
        error: {
            code: 404  + " - Invalid ID"
        }
    });
  }


});

postConfig.json:

// This allow configuration for the POST URL
{
  // I can change to 
  // "URL" : "/api" or any value i want
  "URL" : "/plus" 
}

您可以创建一个地图,例如:

var testMap = {
   1 : "a",
   2 : "b",
   3 : "c"
}

并使用此映射(也可以用作单独的 JSON 文件)而不是 if else 语句

var checkJSONFile = testMap[user.userID];
if(checkJSONFile){
  var contents = fs.readFileSync(publicdir+"/api/"+checkJSONFile+".json");
  var jsonContent = JSON.parse(contents);
  res.send(jsonContent);
}else{
  res.status(404);
  res.json({
    error: {
      code: 404  + " - Invalid ID"
    }
  });
}

更新:

var userId = req.body.userID;
req.body[<key_from_json>] = userId;
// Rest of the code follows