将此代码导出到单独的模块后,为什么此代码无法在NodeJS中运行?

时间:2018-04-14 21:18:36

标签: javascript node.js ecmascript-6 node-modules

我正在使用 exports 对象在不同模块中分离我的API代码,因为它是与ES6标准最相似的方式(不是但得到Node支持。

这是我目前的代码(它可以如图所示运行),问题是,分离后,函数“cleanFormData”被调用为fine,但是在没有返回任何内容的情况下停止(观察注释)以“STACK OVERFLOW”开头:

档案:main.js

// Dependencies:
const express = require('express');
const bodyParser = require('body-parser');

// Define app:
const app = express();

// API v0 code:
const apiV0 = require('./api0_sources/api');

// Configuration variables:
const consoleLogActions = true;

// Server start:
app.listen(8888, function () {
    console.log('Server running on port ' + this.address().port + ' - ' + new Date());
});

// For parsing every application/json request:
app.use(bodyParser.json());

// Submit data to register an user:
app.post('/registration', function (req, res) {

    res.set({'Content-Type': 'application/json'});

    // Clean the required data after obtaining it from the parsed JSON:
    let cleanedFormData = apiV0.cleanFormData({ // STACK OVERFLOW: The code stops working here.
        username: req.body.formdata.username,
        email: req.body.formdata.email,
        phone: req.body.formdata.phone,
        password: req.body.formdata.password
    });

    // The "required or not" policy is enforced here (after the strings have been cleaned to prevent blank fields to pass):
    errors = [];
    if (cleanedFormData.username === undefined)   errors.push('username_required');
    if (cleanedFormData.email === undefined)      errors.push('email_required');
    if (cleanedFormData.phone === undefined)      errors.push('phone_required');
    if (cleanedFormData.password === undefined)   errors.push('password_required');
    if (errors.length > 0) {
        let result = {
            success: false,
            errors: errors
        };

        res.jsonp(result);
    }
})
// [More things happen after]

档案:./ api0_sources / api.js

// Fix and delete object's strings (for data coming from user's inputs):
exports.cleanFormData = function(object) {
    for (let i in object) {
        object[i] = String(object[i]); // Convert all the object properties to strings (to prevent problems with true, false and null).
        if ((object[i] === 'undefined') || (!object[i].replace(/\s/g, '').length)) { // Deletes 'undefined' strings, empty strings and the ones containing only spaces.
            delete object[i];
            continue; // Skip to the next loop after the property is removed.
        }
        // Do not try to fix the "password" or "newPassword" property:
        if ((i === 'password') || (i === 'newPassword')) continue;
        // Replace multiple spaces with a single one:
        object[i] = object[i].replace(/\s\s+/g, ' ');
        // Check if it is "trimmable" and if so, trim the string:
        if (object[i].trim()) object[i] = object[i].trim();
        console.log(object[i]) // Observing iterations.
    }
    if (consoleLogActions) console.log('▼ Cleaned object keys:\n', object);
    return object;
};

之前,所有内容都在同一个文件中并且工作得很好!有人可以帮助我找出导致这种意外行为的原因吗?

更新1:显然,我发现了问题:我之前的示例中没有显示变量:“consoleLogActions”,它只在主文件中定义,显然已停止完成子模块中的功能。但是,Node完全没有抛出任何错误。在更新的例子中,它确实在我的实际文件中没有(仍然不知道为什么)。

更新2:谢谢,Marcos Casagrande。 看起来这个Express中间件正在捕捉错误的异常。我真的不知道这可能会影响代码的其余部分,也不知道如何解决它。 有任何建议吗?

// Detecting syntax errors (depending on the "application/type"):
app.use(function(err, req, res, next) {
    if (err instanceof SyntaxError) { // If "SyntaxError" is part of the error object:
        res
            .status(400)
            .jsonp({
                success: false,
                errors: ['bad_syntax']
            });
    }
});

1 个答案:

答案 0 :(得分:1)

  

显然,我发现了问题:我有一个未显示的变量   之前的例子:" consoleLogActions",这只是在。中定义的   主文件,显然这停止了子模块中的功能   从完成。但是,Node完全没有抛出任何错误。   在更新的例子中,它确实在我的实际文件中它没有(仍然,   不知道为什么)。

如果您没有收到任何错误,您可能会有一个明确的错误处理中间件,它没有记录错误。

app.use((err, req, res, next) => {
    // console.error(err); // I'm not doing this.
    res.status(500).end();
});

或者您的代码中有一个uncaughtException侦听器。

process.on('uncaughtException', () => {}); 

上面的代码将防止记录未捕获的错误,并防止崩溃的过程。这是一个非常糟糕的做法,你应该避免它。

检查以下问题:

Node.js Best Practice Exception Handling