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'));
Related
I'm setting up express server with create-react-app.
AT console I'm getting
Uncaught SyntaxError: Unexpected token < bundle.js:1
When I click on error it shows me homepage html.
While using morgan logger its giving me 200 ok.
GET /static/js/bundle.js 304 1.145 ms - -
Also when i view source click on css link it shows me css while click on javascript link it shows me blank page(homepage html).
Here is the the server code.
var express = require('express');
var bodyParser = require('body-parser');
var logger = require('morgan');
var path = require ('path');
var data = {};
express()
.use(logger('dev'))
.use(express.static(path.join(__dirname, 'flashcard-app/build')))
.use(bodyParser.json())
.get('/api/test', (req, res) => res.json("Great news every thing is working fine."))
.get('/api/data', (req, res) => res.json(data))
.post('/api/data', (req, res) => res.json(data = req.body))
.get('*', function(req, res) {
console.log('serving path:', path.join(__dirname+'/flashcard-app/build/index.html'));
res.sendFile(path.join(__dirname, 'flashcard-app/build/index.html'));
})
.listen(3333, function(){
console.log('server running at 3333');
});
Also this is custom server.js file not one that provided by express-generator. I'm running by node server_old.js instead of using ./bin/www
Help comment tips appreciated.
You are trying to fetch /static/js/bundle.js, but there is no bundle.js in static/js.
I think you are trying to use index.html that tries to bundle.js while your webpack config builds main.[hash].js
Folder structure
bin - www.js
lib - jsFiles...
models - jsFiles...
node_modules -Folders and Files
public - index.html
route - jsFiles...
index.js
package.json
I use Express, angular.js. Server starts at www.js and It calls
index.js. After that, When I type merely "localhost:3000" It shows me
public/index.html. I don't have route for '/' but It shows me
'public/index.html'. I can not understand this. Please let me know
about the process.
www.js
var debug = require('debug')('example-server');
var app = require(process.cwd()+'/index');
//listen at 3000 port
app.set('port',process.env.PORT || 3000);
var server = app.listen(app.get('port'),function()
{
debug('Express server listening on port ' + server.address().port);
});
index.js
var favicon = require('serve-favicon');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//Connection for DB
require('./lib/connection');
var employees = require('./routes/employees');
var teams = require('./routes/teams');
var app = express();
// Writing at routing table
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname,'public')));
app.use(employees);
app.use(teams);
// send 404 to errorhandler
app.use(function(err,req,res,next)
{
var err = new Error('Not Found');
err.status = 404;
console.log(error);
next(error);
});
...
...
module.exports = app;
In express.js the sequence in which you register your middleware makes a huge difference.
When express.js receives a request, it starts from top and executes registered middleware.
Middlewares are registered in express app using app.use(middleware_goes_here) this type of middleware gets executed no matter what the request url is on the other hand you can also register a middleware like app.use('/url/path',middleware_goes_here) in this case we are registering this middleware to '/url/path' so this middleware will only get executed when you visit '/url/path' (and non of the previous matching middleware serves the request without calling next() )
This app.use(express.static(path.join(__dirname,'public'))); line of code does the magic.
You can go here (express.static ref) to know more about static content serving and routing.
Basically what happens is, we are configuring express.static middleware to serve static content "as is" from "public" folder. So when you make any request and it matches a static content in public folder, then it will serve it otherwise express.static will call next middleware in sequence.
So in your case, the first middleware that actually server input request is express.static without any route filters, so it servers index.html even without a specifically defined route. If your public folder had file at public/javascript/jquery.js then following url will map to it http://localhost:3000/javascript/jquery.js
NOTE: You do not have to specify "public" in the url, the way in which express.static is registered, it will server contents FROM "public" folder.
................
UPDATE: How does default work in express.static?
By default, app.use(express.static(path.join(__dirname,'public'))); this will take index.html as default document. If you want to set index2.html as your default document, you can do that by doing something like this app.use(express.static(path.join(__dirname,'public'),{index: 'index2.html'}));
Hope it helps.
Put a relative path to folder(one up in hierarchy).
var app = require('../index');
I'm trying to make node (or express? I'm still a noob so I don't know which is doing the actual work here) render views from multiple folders. So if I have a log in page, then there is a separate folder with index.ejs for log in, and other files for log in. and for my main page, a different folder with index etc...
I found this link which was helpful https://strongloop.com/strongblog/bypassing-express-view-rendering-for-speed-and-modularity/ however they give examples for the jade rendering engine and marko. I'm using ejs and I'm trying the examples they have but they're not working. For example:
I tried this one:
var templatePath = require.resolve('./template.jade');
var templateFn = require('jade').compileFile(templatePath);
app.get('/', function (req, res) {
res.write(templateFn({name: 'Frank'});
res.end();
});
but I replaced require('jade') with require('ejs') but then I get an error on compileFile(templatePath):
undefined is not a function
I also tried the other example with marko
var templatePath = require.resolve('./template.marko');
var template = require('marko').load(templatePath);
app.get('/', function (req, res) {
template.render({name: 'Frank'}, res);
});
but got the same error on load(templatePath). I can't figure out how to make node render views from locations other than the root views folder
ejs only has a compile() function that takes in a string version of the template as an argument. So you will need to load the template from disk manually first:
var fs = require('fs');
var templatePath = require.resolve('./template.ejs');
var template = require('ejs').compile(fs.readFileSync(templatePath, 'utf8'));
app.get('/', function (req, res) {
res.end(template({name: 'Frank'}));
});
I am trying to get Cheerio to work with Express.
I'd like to be able to manipulate the dom from the server, but all I have found is web scraping..
There are some requirements..
At the moment, I am able to run multiple app.listen(port); statements, and use multiple servers.
I'm trying to append <script>alert("test);</script> to every single page sent by express.
I've created the express server: (Assuming Path is a predefined variable)
var express = require('express');
var app = express();
app.get('/', function (req, res) {
app.use(app.static(Path));
res.sendFile(Path + "/index.html");
});
app.listen(Port);
Can you guys provide me with a working example to append this to the page. Is there a way to get this to work in real time?
Thanks!
Here's a quick/simple example with no error handling:
var express = require('express');
var fs = require('fs');
var cheerio = require('cheerio');
var app = express();
app.get('/', function (req, res) {
fs.readFile(Path + '/index.html', function(err, data) {
var $ = cheerio.load(data);
$('body').append('<script>alert("test");</script>');
res.send($.html());
});
});
app.listen(Port);
I just tested that locally and it worked as expected. Be sure to test err inside the readFile callback in your real implementation and handle things appropriately if the file isn't found or there's an error reading it.
I'm getting around to using domains and am trying a couple of Express domain middleware packages:
https://github.com/brianc/node-domain-middleware
https://github.com/baryshev/connect-domain
According to the usage docs on the first one I should have access to process.domain but it is undefined.
I am basically doing this in my app.js
var express = require('express'),
domains = require('express-domain-middleware');
var app = exports.app = express();
app.use(domains);
And in a controller:
exports.index = function(req, res, next) {
console.log(process.domain); //undefined
};
What gives?
You might want to check (using console.log or breakpoints) to make sure this line is happening before your index method is getting called:
express.use(domain);
I don't know how your app is structured but order of app.use is usually the case.
Your app.get('/someurl', yourcontroller.index) should come after app.use(domain).
Ok - it's due to a Mongo call in my middleware. Evidently all database calls have to be wrapped.
var d = domain.create();
d.run(function () {
client.query('...', d.intercept(function (rows) {
// ... use rows (note, first arguments error was "intercepted" by the domain)
}));
});
Reference: https://github.com/felixge/node-mysql/issues/308