在nodejs服务器上提供文件的更好方法,而不是if/else

better method for serving files on nodejs server instead of if/else

本文关键字:if else 方法 更好 服务器 nodejs 文件      更新时间:2023-10-29

我有一个端点,它提供一个文件供用户根据用户在网页上的选择下载。然而,根据用户选择的可能性,我能想到的解释这一切的唯一方法是使用if/else语句。

router.post('/process', function(req, res) {
    if(req.query.os == 'Windows' && req.query.rec == 'Computer Information' && req.query.report == 'Local Report') {
        res.send('http://localhost:3033/proc/windows/info/local/files.zip');
    } else if (req.query.os == 'Windows' && req.query.rec == 'User Information' && req.query.report == 'Local Report') {
        res.send('http://localhost:3033/proc/windows/uinfo/local/files.zip');
    }
}

如果我添加Linux或OSX的选项,我也必须考虑这些选项,结果代码会变得非常长和丑陋。有没有更好的方法让我解释这件事?

您可以将变量转换为url部分。它将更容易维护。例如:

router.post('/process', function(req, res) {
    var url_parts = {
        'os' : {
            'Windows' : 'windows',
            'Linux' : 'linux',
            'OSX' : 'mac'
        },
        'rec' : {
            'Computer Information' : 'info',
            'User Information' : 'uinfo'
        },
        'report' : {
            'Local Report' : 'local',
            'Global Report' : 'global'
        }
    };
    res.send(
        'http://localhost:3033/proc/'
        + url_parts.os[req.query.os]
        + '/' + url_parts.rec[req.query.rec]
        + '/' + url_parts.report[req.query.report]
        + '/files.zip'
        );
});