【问题标题】:NodeJS Express - How to Create Configuration File for POST Request?NodeJS Express - 如何为 POST 请求创建配置文件?
【发布时间】:2018-10-12 06:05:22
【问题描述】:

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

我的愿望输出:

是否可以使用 JSON 或 YAML 创建配置文件,允许用户在想要添加更多 Post Request Input 并添加更多条件时编辑配置文件以打开 JSON File 而不是手动打开向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" 
}

【问题讨论】:

    标签: javascript node.js express configuration configuration-files


    【解决方案1】:

    您可以创建地图,例如:

    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
    

    【讨论】:

    • 是的,可以,但它只会在服务器重新启动时从文件中获取端点。
    • 您愿意更新您的代码解决方案以获得更好的说明吗?也许这是我正在寻找的实现。
    • “POST 输入(用户 ID)变得可配置”到底是什么意思?
    • 我已经更新了代码,如果解决了你的问题,标记为答案。
    • 请撤消您的答案解决方案回到您的第一个答案,忘记我在评论中提到的内容。我已经更新了我的问题并在我的代码中写了评论,以清楚地解释我想要什么。请再次查看我的问题,您会明白的。谢谢。
    猜你喜欢
    • 2019-06-26
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 2015-06-26
    • 2018-06-16
    • 1970-01-01
    • 2013-08-28
    • 2016-01-31
    相关资源
    最近更新 更多