简体   繁体   English

Node.js参考错误:索引未定义

[英]Node.js reference error: index is not defined

I am building a chat application, and this index.js file is in the "routes" directory. 我正在构建一个聊天应用程序,并且此index.js文件位于“ routes”目录中。 The error is on the first line. 错误在第一行。 There is also an index.jade file in the "views" directory. “视图”目录中还有一个index.jade文件。

module.exports.index = index;
module.exports.logon = logon;
module.exports.message = message;

exports.index = function index(req, res){
  res.render('index');
};

function logon(req, res){
  res.send('Logon');
};

function message(req, res){
  res.send('Message');
};

You are doing exports two times, also there is no variable index . 您执行两次exports ,也没有变量index

exports.index = function index(req, res){
  res.render('index');
};

module.exports.index = index;

try using 尝试使用

module.exports.index = index;

var index = function(req,res) {
  res.render('index');
}

When you assign a function to a variable, or you immediately call a function, you turn it from a statement into an expression. 当您将函数分配给变量或立即调用函数时,会将其从语句转换为表达式。 This causes function hoisting to not happen. 这导致功能提升没有发生。 You can fix the issue by not assigning the function index to exports.index , to restore the hoisting behavior: 您可以通过不将函数index分配给exports.index来解决此问题,以恢复提升行为:

function index(req, res){
  res.render('index');
};

You'll still have problem after that, because logon and message are not defined (you've defined login and chat instead). 之后,您仍然会遇到问题,因为未定义logonmessage (您已定义了loginchat )。

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

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