I keep getting an error that says it cannot find the module reddit.js. I have a folder called "routes" (without quotes) in my directory. In that folder I have reddit.js which is middleware. 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 "
When I keep the code as shown below I get this error:
Error: Cannot find module 'reddit.js'
my app.js file contains the following code:
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:
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. Use require('/path/to/reddit');
instead of require('reddit.js');
You need to export the router instance in reddit.js
. Add module.exports = reddit;
at the end of the file.
Don't call next()
after sending out the response using res.send(docs);
Routes are not static content. Remove app.use(express.static('routes'));
app.use(express.static('/public'));
handles all static content inside the /public
folder. You do not need to add app.use(express.static('/public/js'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.