我的路由index.js文件出错(找不到模块)

时间:2016-11-26 06:28:19

标签: javascript node.js express

错误显示“无法找到模块'./routes/index'”但显然它位于该文件夹中(即使静态设置为该文件夹)

这是错误:

root@ip*censored*:/home/ubuntu/*censored*# module.js:471
    throw err;
    ^

Error: Cannot find module './routes/index'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/ubuntu/*censored*/routes/index.js:7:14)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)

以下是我的目录:

-bin
-forbiddenDirectory
-Node_modules
-public
-routes
-----index.js
-----users.js
-views
app.js
main.js
bundle.js
package.json

这是在我的app.js:

var routes = require("./routes/index");
app.use('/', routes);

这是我的index.js:

var express = require('express');
var router = express.Router();
var app = express();
var aws = require('aws-sdk');
var request = require('request');
var cheerio = require('cheerio');
var routes = require('./routes/index');
var fs = require('fs');
var url = "http://news.google.com";
var ep = new aws.Endpoint('censored.us-west-1.censored.com');
var db = new aws.DynamoDB.DocumentClient({      // Dynamo database constructor
    "apiVersion": '2012-08-10',
    "region": 'us-west-1',
    "endpoint": ep,
    "accessKeyId": 'censored',
    "secretAccessKey": '+censored/censored'
});
var dateObj = new Date();
var dbTimeStamp = dateObj.toLocaleString();

// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
  next();
});


/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index');
});

//module.exports = router;
module.exports = function(req,res,next) { res.render('index')}

因此它显然位于routes文件夹中,但由于某种原因它不会读取它。我尝试了一切...我尝试将./routes/index更改为./routes/index.js,转换为./routes/,然后转换为./routes,然后转换为/ routes,然后尝试路由/索引/,然后执行../路由/索引与之后的.js相同。我放弃了,需要你的帮助。 谢谢。

4 个答案:

答案 0 :(得分:3)

尝试添加文件扩展名。所以app.js中的代码将是:

var routes = require("./routes/index.js"); 
app.use('/', routes);

答案 1 :(得分:1)

您应该在index.js中使用此代码:

exports.index=function(req,res,next){
  res.render('index');
}
app.js中的

app.use('/', routes.index);

答案 2 :(得分:1)

请删除routes = require(&#39; ./ routes / index&#39;);来自index.js

答案 3 :(得分:0)

检查模块文件的文件扩展名和文件名