[英]Why is this code not working in NodeJS after exporting it to a separate module?
我正在使用导出对象将API代码分离到不同模块中的方式,因为这与ES6标准(Node尚不支持)最相似。
这是我的当前代码(可以按所示方式运行),问题是,分离后, 函数“ cleanFormData”被调用为好,但是在不返回任何内容的情况下停止了 (观察以“ 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:谢谢,马科斯·卡萨格兰德。 看来,这种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']
});
}
});
显然,我发现了问题:我有一个变量在前面的示例中未显示:“ consoleLogActions”,该变量仅在主文件中定义,显然这阻止了子模块中的功能完成。 但是,Node绝对不会抛出任何错误。 在更新的示例中,它确实存在,但在我的实际文件中却没有(仍然,不知道为什么)。
如果没有收到任何错误,则可能是有一个明确的错误处理中间件,它没有记录错误。
app.use((err, req, res, next) => {
// console.error(err); // I'm not doing this.
res.status(500).end();
});
或者,您在代码中的某个地方有一个uncaughtException侦听器。
process.on('uncaughtException', () => {});
上面的代码将防止记录未捕获的错误,并防止进程崩溃。 这是一个非常糟糕的做法,应避免这样做。
检查以下问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.