简体   繁体   English

尝试将中间件功能导出到module.exports对象时,为什么会得到“下一个不是功能”的信息?

[英]Why do I get 'Next is not a function' when I try to export a Middleware function to module.exports object?

I have a middleware function written inside my logger.js module which I then import into app.js and use 我在logger.js模块中编写了一个中间件函数,然后将其导入到app.js并使用

 // ------ File : logger.js ------ // function log(req, res, next) { console.log('Logging details ... '); next(); } module.exports = log; // ------ File : app.js -------- // const logger = require('./logger'); app.use(logger); 

The above code works without any issue and my log functionality works. 上面的代码可以正常工作,我的日志功能也可以工作。 However, if I export this log function in the following way (add it to the module.exports object), I get an error 但是,如果我以以下方式导出此日志功能(将其添加到module.exports对象), module.exports收到错误消息

 // ------ File : logger.js -------// function log(req, res, next) { console.log('Logging details ... '); next(); } module.exports.log = log; // ------ File : app.js -------- // const logger = require('./logger'); app.use(logger.log()); 

 Logging details ... D:\\express-demo-worked\\logger.js:4 next(); ^ TypeError: next is not a function at Object.log (D:\\express-demo-worked\\logger.js:4:5) at Object.<anonymous> (D:\\express-demo-worked\\app.js:18:16) at Module._compile (internal/modules/cjs/loader.js:738:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:749:10) at Module.load (internal/modules/cjs/loader.js:630:32) at tryModuleLoad (internal/modules/cjs/loader.js:570:12) at Function.Module._load (internal/modules/cjs/loader.js:562:3) at Function.Module.runMain (internal/modules/cjs/loader.js:801:12) at internal/main/run_main_module.js:21:11 [nodemon] app crashed - waiting for file changes before starting... 

Can someone explain to me why this behaves differently and how to correct the second code snippet I added here? 有人可以向我解释为什么这种行为会有所不同,以及如何纠正我在此处添加的第二个代码段吗?

app.use(logger.log());

This will call logger.log immediately, passing in no arguments. 这将立即调用logger.log,不传递任何参数。 Whatever logger.log returns will then be passed into app.use. 不管logger.log返回什么,都将传递到app.use中。 Since you passed in no arguments, next is undefined, resulting in that exception. 由于您未传入任何参数,因此next是未定义的,从而导致该异常。

Instead, do: 相反,请执行以下操作:

app.use(logger.log);

This will pass logger.log into app.use. 这会将logger.log传递到app.use中。 At some point later, logger.log will be called, passing in the correct arguments. 稍后,将调用logger.log,并传递正确的参数。

Here: 这里:

app.use(logger.log());

you're calling log , without any arguments, and passing its return value into app.use . 您正在调用 log (不带任何参数),并将其返回值传递到app.use Since log expects and uses its parameters, that will fail on next() because the value of the next parameter is undefined , as you didn't pass an argument for it. 由于log期望并使用其参数,因此在next()上将失败,因为next参数的值是undefined ,因为您没有为其传递参数。

You may have meant just to pass the function in: 您可能只是想将函数传递给:

app.use(logger.log);
// No () ---------^

如何修复“无法分配给 object 的只读属性“导出”'#<object> ' 将第二个 function 添加到 module.exports 时?<div id="text_translate"><p> 不幸的是,我已经被困了大约 5 天了。 我用谷歌搜索过,没有什么对我有用。 我有一个 utils.js 文件,里面有很多东西可以帮助我。 当我将 function "doesUserContainRoles" 添加到导出时,我的 Chrome 控制台给了我错误:</p><blockquote><p> Uncaught TypeError: Cannot assign to read only property 'exports' of object '#&lt;Object&gt;'</p></blockquote><p> 当我删除 function 时,utils 文件中的所有内容都可以完美运行,根本没有 0 个问题。 只要我添加 function,我就会收到此错误。 我通过以下方式要求 utils 文件:</p><pre class="lang-js prettyprint-override"> const utils = require("../../../utils");</pre><p> 并且没有与此一起使用的import 。 (我知道module.exports和import不能一起工作)</p><p> 我正在使用什么:</p><ul><li><p> Vue.js @vue/cli 4.5.8</p></li><li><p> Node.js v15.2.0</p></li></ul><h3> 文件:</h3><p> utils.js</p><pre class="lang-js prettyprint-override"> const winston = require("winston"); const { datadog } = require("./credentials.js"); const { createLogger, format, transports } = require('winston'); const base_url = "http://localhost:3001/api/v1" // Winston ~ const httpTransportOptions = { host: datadog.logger.host, path: datadog.logger.path, ssl: datadog.logger.ssl }; const customLevels = { levels: { emergency: 0, alert: 1, critical: 2, error: 3, warn: 4, notice: 5, info: 6, debug: 7, success: 8 }, } const logger = createLogger({ level: 'info', levels: customLevels.levels, exitOnError: false, format: format.json(), transports: [ new transports.Http(httpTransportOptions), ], }); const commonMessages = { accessPage: "User Accessed a Page", restrictedPage: "Attempt at accessing restricted page" } function alertGeneral() { alert("Oops. An error has occurred. Please try again later, If this problem continues. please contact Vinniehat;"), } function doesUserContainRoles(userRoles. containsRoles) { return.;userRoles.some(role =&gt; containsRoles,includes(role)), } module,exports = { logger, commonMessages, base_url, alertGeneral, doesUserContainRoles }</pre><p> 这是错误堆栈:</p><pre> Uncaught TypeError: Cannot assign to read only property 'exports' of object '#&lt;Object&gt;' at Module.eval (utils.js?1b23:45) at eval (utils.js:68) at Module../utils.js (app.js:1944) at __webpack_require__ (app.js:854) at fn (app.js:151) at eval (router.js?9883:19) at Module../src/router/router.js (app.js:1812) at __webpack_require__ (app.js:854) at fn (app.js:151) at eval (main.js:34)</pre><p> 我也尝试使用export default 。 这样做时,我的前端工作。 网站加载没有错误。 不过,我的后端使用 Express.js 运行,然后引发错误:</p><pre> Unhandled rejection E:\Development\Websites\iceberg-gaming-website\utils.js:45 export default { ^^^^^^ SyntaxError: Unexpected token 'export' at wrapSafe (node:internal/modules/cjs/loader:1018:16) at Module._compile (node:internal/modules/cjs/loader:1066:27) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10) at Module.load (node:internal/modules/cjs/loader:967:32) at Function.Module._load (node:internal/modules/cjs/loader:807:14) at Module.require (node:internal/modules/cjs/loader:991:19) at require (node:internal/modules/cjs/helpers:92:18) at Object.&lt;anonymous&gt; (E:\Development\Websites\iceberg-gaming-website\express\modules\user.js:9:15) at Module._compile (node:internal/modules/cjs/loader:1102:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10) at Module.load (node:internal/modules/cjs/loader:967:32) at Function.Module._load (node:internal/modules/cjs/loader:807:14) at Module.require (node:internal/modules/cjs/loader:991:19) at require (node:internal/modules/cjs/helpers:92:18) at E:\Development\Websites\iceberg-gaming-website\express\express.js:27:27 at tryCatcher (E:\Development\Websites\iceberg-gaming-website\node_modules\bluebird\js\release\util.js:16:23)</pre></div></object> - How do I fix 'Cannot assign to read only property 'exports' of object '#<Object>' when adding a 2nd function to module.exports?

暂无
暂无

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

相关问题 如何通过 module.exports 导出这个名为 function 的文件? - How do I export this named function through module.exports? 如何修复“无法分配给 object 的只读属性“导出”'#<object> ' 将第二个 function 添加到 module.exports 时?<div id="text_translate"><p> 不幸的是,我已经被困了大约 5 天了。 我用谷歌搜索过,没有什么对我有用。 我有一个 utils.js 文件,里面有很多东西可以帮助我。 当我将 function "doesUserContainRoles" 添加到导出时,我的 Chrome 控制台给了我错误:</p><blockquote><p> Uncaught TypeError: Cannot assign to read only property 'exports' of object '#&lt;Object&gt;'</p></blockquote><p> 当我删除 function 时,utils 文件中的所有内容都可以完美运行,根本没有 0 个问题。 只要我添加 function,我就会收到此错误。 我通过以下方式要求 utils 文件:</p><pre class="lang-js prettyprint-override"> const utils = require("../../../utils");</pre><p> 并且没有与此一起使用的import 。 (我知道module.exports和import不能一起工作)</p><p> 我正在使用什么:</p><ul><li><p> Vue.js @vue/cli 4.5.8</p></li><li><p> Node.js v15.2.0</p></li></ul><h3> 文件:</h3><p> utils.js</p><pre class="lang-js prettyprint-override"> const winston = require("winston"); const { datadog } = require("./credentials.js"); const { createLogger, format, transports } = require('winston'); const base_url = "http://localhost:3001/api/v1" // Winston ~ const httpTransportOptions = { host: datadog.logger.host, path: datadog.logger.path, ssl: datadog.logger.ssl }; const customLevels = { levels: { emergency: 0, alert: 1, critical: 2, error: 3, warn: 4, notice: 5, info: 6, debug: 7, success: 8 }, } const logger = createLogger({ level: 'info', levels: customLevels.levels, exitOnError: false, format: format.json(), transports: [ new transports.Http(httpTransportOptions), ], }); const commonMessages = { accessPage: "User Accessed a Page", restrictedPage: "Attempt at accessing restricted page" } function alertGeneral() { alert("Oops. An error has occurred. Please try again later, If this problem continues. please contact Vinniehat;"), } function doesUserContainRoles(userRoles. containsRoles) { return.;userRoles.some(role =&gt; containsRoles,includes(role)), } module,exports = { logger, commonMessages, base_url, alertGeneral, doesUserContainRoles }</pre><p> 这是错误堆栈:</p><pre> Uncaught TypeError: Cannot assign to read only property 'exports' of object '#&lt;Object&gt;' at Module.eval (utils.js?1b23:45) at eval (utils.js:68) at Module../utils.js (app.js:1944) at __webpack_require__ (app.js:854) at fn (app.js:151) at eval (router.js?9883:19) at Module../src/router/router.js (app.js:1812) at __webpack_require__ (app.js:854) at fn (app.js:151) at eval (main.js:34)</pre><p> 我也尝试使用export default 。 这样做时,我的前端工作。 网站加载没有错误。 不过,我的后端使用 Express.js 运行,然后引发错误:</p><pre> Unhandled rejection E:\Development\Websites\iceberg-gaming-website\utils.js:45 export default { ^^^^^^ SyntaxError: Unexpected token 'export' at wrapSafe (node:internal/modules/cjs/loader:1018:16) at Module._compile (node:internal/modules/cjs/loader:1066:27) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10) at Module.load (node:internal/modules/cjs/loader:967:32) at Function.Module._load (node:internal/modules/cjs/loader:807:14) at Module.require (node:internal/modules/cjs/loader:991:19) at require (node:internal/modules/cjs/helpers:92:18) at Object.&lt;anonymous&gt; (E:\Development\Websites\iceberg-gaming-website\express\modules\user.js:9:15) at Module._compile (node:internal/modules/cjs/loader:1102:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10) at Module.load (node:internal/modules/cjs/loader:967:32) at Function.Module._load (node:internal/modules/cjs/loader:807:14) at Module.require (node:internal/modules/cjs/loader:991:19) at require (node:internal/modules/cjs/helpers:92:18) at E:\Development\Websites\iceberg-gaming-website\express\express.js:27:27 at tryCatcher (E:\Development\Websites\iceberg-gaming-website\node_modules\bluebird\js\release\util.js:16:23)</pre></div></object> - How do I fix 'Cannot assign to read only property 'exports' of object '#<Object>' when adding a 2nd function to module.exports? module.exports不会导出具有功能的对象 - module.exports won't export object with function 如何在节点 js 中使用 module.exports 导出数组? - How do I export an array with module.exports in node js? 带函数的 module.exports - module.exports with function module.exports:不是函数 - module.exports: is not a function 为什么在使用 module.exports 时出现“not a function”错误? - Why "not a function" error when using module.exports? 我没有从module.exports得到答案 - I do not get an answer from module.exports module.exports在哪里导出您的函数,以及当我们仍在使用require时,将代码导入您的模块的用途是什么? - where do module.exports export your function and what is the use of it when we still use require to import the code into your module module.exports函数不是函数 - module.exports function is not a function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM