【发布时间】: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