简体   繁体   English

表达错误-找不到模块-静态文件

[英]express error - cannot find module - static file

I keep getting an error that says it cannot find the module reddit.js. 我不断收到错误消息,指出找不到模块reddit.js。 I have a folder called "routes" (without quotes) in my directory. 我的目录中有一个名为“ routes”的文件夹(不带引号)。 In that folder I have reddit.js which is middleware. 在该文件夹中,我有作为中间件的reddit.js。 On the first file below, I did change it to var reddit = require('./routes/reddit.js') and I received the error messsage that says "throw new TypeError('Router.use() requires middleware function but got a ^ TypeError: Router.use() requires middleware function but got a Object at Function.use " 在下面的第一个文件上,我确实将其更改为var reddit = require('./ routes / reddit.js'),并且收到错误消息,内容为“抛出新的TypeError('Router.use()需要中间件功能,但一个^ TypeError:Router.use()需要中间件功能,但在Function.use处有一个对象

When I keep the code as shown below I get this error: 当我保留如下所示的代码时,出现此错误:

Error: Cannot find module 'reddit.js' 错误:找不到模块“ reddit.js”


my app.js file contains the following code: 我的app.js文件包含以下代码:

var express = require('express');
var app = express();
var fs = require('fs');
var reddit = require('reddit.js');

app.use ('/', reddit);
app.use(express.static('public'));
app.use(express.static('public/js'));
app.use(express.static('public/images'));
app.use(express.static('routes'));

my reddit.js file contains the following code: 我的reddit.js文件包含以下代码:

var express = require ('express');
var request = require ('request');
var reddit = express.Router();

reddit.get(function (req, res, next) {
    request('https://www.reddit.com/r/Showerthoughts/hot.json',function(error, response, body){
        console.log(body);
        var docs = JSON.parse(body).response;
        //var titles = [];
        console.log(docs);
        res.send(docs);
        next;
    });
});

what am I doing wrong? 我究竟做错了什么?

Mentioned below are the list of things that are not correct 下面提到的是不正确的内容列表

  • You don't need to have .js extensions for including files. 您不需要具有.js扩展名即可包含文件。 Use require('/path/to/reddit'); 使用require('/path/to/reddit'); instead of require('reddit.js'); 而不是require('reddit.js');

  • You need to export the router instance in reddit.js . 您需要在reddit.js导出路由器实例。 Add module.exports = reddit; 添加module.exports = reddit; at the end of the file. 在文件末尾。

  • Don't call next() after sending out the response using res.send(docs); 使用res.send(docs);发送响应后,请勿调用next() res.send(docs);

  • Routes are not static content. 路由不是静态内容。 Remove app.use(express.static('routes')); 删除app.use(express.static('routes'));

  • app.use(express.static('/public')); handles all static content inside the /public folder. 处理/public文件夹中的所有静态内容。 You do not need to add app.use(express.static('/public/js')); 您不需要添加app.use(express.static('/public/js'));

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

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