简体   繁体   English

将其导出到单独的模块后,为什么此代码在NodeJS中不起作用?

[英]Why is this code not working in NodeJS after exporting it to a separate module?

I am on my way to separate the code for my API in different modules using the exports object, as it is the most similar way to the ES6 standard (not yet supported by Node). 我正在使用导出对象将API代码分离到不同模块中的方式,因为这与ES6标准(Node尚不支持)最相似。

Here is my code currently (it can be run as shown), the problem is that, after separating, the function "cleanFormData" gets called fine, but stops without returning anything (observe the comments starting with "STACK OVERFLOW"): 这是我的当前代码(可以按所示方式运行),问题是,分离后, 函数“ cleanFormData”被调用为好,但是在不返回任何内容的情况下停止了 (观察以“ STACK OVERFLOW”开头的注释):

File: main.js 档案: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]

File: ./api0_sources/api.js 文件:./ 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;
};

Before, everything was in the same file and worked perfectly fine! 以前,所有内容都在同一个文件中,并且运行良好! Can someone help me to identify what has triggered this unexpected behaviour? 有人可以帮助我确定是什么触发了这种意外行为吗?

UPDATED 1: Apparently, I identified the problem: I had a variable not shown in the example before: "consoleLogActions", that was only defined in the main file and apparently this stopped the function in the child module from finishing . 更新1:显然,我发现了问题:我有一个变量在前面的示例中未显示: “ consoleLogActions”,该变量仅在主文件中定义,显然这阻止了子模块中的函数完成 However, absolutely no error was being thrown by Node. 但是,Node绝对不会抛出任何错误。 In the updated example it does, in my actual file it doesn't (still, no idea why). 在更新的示例中,它确实存在,但在我的实际文件中却没有(仍然,不知道为什么)。

UPDATE 2: Thanks, Marcos Casagrande. 更新2:谢谢,马科斯·卡萨格兰德。 It seems like this Express middleware is catching the wrong exceptions . 看来,这种Express中间件正在捕获错误的异常 I had literally no idea that this could affect the rest of the code nor I have idea how to fix it. 我真的不知道这可能会影响其余的代码,也不知道如何解决它。 Any suggestions? 有什么建议么? :

// 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']
            });
    }
});

Apparently, I identified the problem: I had a variable not shown in the example before: "consoleLogActions", that was only defined in the main file and apparently this stopped the function in the child module from finishing. 显然,我发现了问题:我有一个变量在前面的示例中未显示:“ consoleLogActions”,该变量仅在主文件中定义,显然这阻止了子模块中的功能完成。 However, absolutely no error was being thrown by Node. 但是,Node绝对不会抛出任何错误。 In the updated example it does, in my actual file it doesn't (still, no idea why). 在更新的示例中,它确实存在,但在我的实际文件中却没有(仍然,不知道为什么)。

If you're not getting any error, you probably have an express error-handling middleware, that it's not logging the error. 如果没有收到任何错误,则可能是有一个明确的错误处理中间件,它没有记录错误。

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

Or you have an uncaughtException listener somewhere in your code. 或者,您在代码中的某个地方有一个uncaughtException侦听器。

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

The code above, will prevent uncaught errors from being logged, and the process from crashing. 上面的代码将防止记录未捕获的错误,并防止进程崩溃。 This is a really bad practice, and you should avoid it. 这是一个非常糟糕的做法,应避免这样做。

Check the following question: 检查以下问题:

Node.js Best Practice Exception Handling Node.js最佳实践异常处理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM