gpt4 book ai didi

javascript - 为什么这段代码在导出到单独的模块后在 NodeJS 中不起作用?

转载 作者:行者123 更新时间:2023-12-03 02:05:24 25 4
gpt4 key购买 nike

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

这是我当前的代码(可以如图所示运行),问题是,分离后,函数“cleanFormData”被很好地调用,但停止而不返回任何内容(观察注释从“堆栈溢出”开始):

文件: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']
});
}
});

最佳答案

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', () => {}); 

上面的代码将防止记录 Uncaught Error 以及进程崩溃。这是一种非常糟糕的做法,您应该避免它。

检查以下问题:

Node.js Best Practice Exception Handling

关于javascript - 为什么这段代码在导出到单独的模块后在 NodeJS 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49836299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com