为什么这段代码在导出到一个单独的模块后不能在 NodeJS 中运行?
Why is this code not working in NodeJS after exporting it to a separate module?
我正在使用 exports 对象在不同的模块 中分离我的 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.js 绝对没有抛出任何错误。在更新的示例中它是,在我的实际文件中它没有(仍然不知道为什么)。
更新 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']
});
}
});
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. However, absolutely no error was being thrown by Node.
In the updated example it does, in my actual file it doesn't (still,
no idea why).
如果您没有收到任何错误,您可能有一个快速错误处理中间件,它没有记录错误。
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
我正在使用 exports 对象在不同的模块 中分离我的 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.js 绝对没有抛出任何错误。在更新的示例中它是,在我的实际文件中它没有(仍然不知道为什么)。
更新 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']
});
}
});
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. However, absolutely no error was being thrown by Node. In the updated example it does, in my actual file it doesn't (still, no idea why).
如果您没有收到任何错误,您可能有一个快速错误处理中间件,它没有记录错误。
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