I know some JS but I'm new to Node.js. I know this is a very common error but I couldn't find the source of the error since I lack debugging skills in Node.js.
Here is my app.js :
var index = require('./routes/index');
var users = require('./routes/userlist');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/userlist', users);
Here is my userlist.js :
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
Here is my index.js:
var express = require('express');
var router = express.Router();
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
console.log(collection);
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
Here is userlist view :
extends layout
block content
h1.
User List
ul
each user, i in userlist
li
a(href="mailto:#{user.email}")= user.username
I appreciate if you tell me where the problem is or tell me how I can detect the problem. Thanks in advance.
EDIT:
In console I get this :
GET /userlist 500 296.280 ms - 1501
EDIT 2:
It gives me the error at this line :
var collection = db.get('usercollection');
EDIT 3:
In index.js, I see that
router.get('/userlist', function(req, res) {
var db = req.db;
req.db is undefined. Why is it undefined? Do you have any idea?
Changing code to this worked:
app.use(function(req,res,next){
req.db = db;
next();
});
app.use('/', index);
app.use('/userlist', users);
Change your code accordingly:
userlist.js
var express = require('express').Router();
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
index.js
var express = require('express').Router();
var router = express.Router();
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
console.log(collection);
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
You should use var router = require('express').Router(); instead of var router = require('express');
Related
I am setting up a site on Express.JS with express-generator but ran into a hiccup with the routing. Currently I keep receiving the "error" view and a 404 message whenever sending a GET request to another route I set up ("/hook"). Currently the two routes that are working is "/" which goes to the "index" and "/users" which goes responds a message. I would like to see why I am getting this error as the others work.
Here is the app.js file:
var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");
var hookRouter = require("./routes/hook");
var app = express();
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/hook", hookRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// // error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
// // render the error page
res.status(err.status || 500);
res.render("error");
});
module.exports = app;
Here is the index router
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
Here is the hook router:
var express = require("express");
var router = express.Router();
/* GET hook page. */
router.get("/hook", function (req, res) {
res.send("Hook Page Works");
});
module.exports = router;
Please let me know there is any more info I can give. Thanks!
The hook router needs to be:
/* GET hook page. */
router.get("/", function (req, res) {
res.send("Hook Page Works");
});
This:
app.use("/hook", hookRouter);
has already used the /hook part of the path so within the router, you just want /.
Your original combination of:
app.use("/hook", hookRouter);
router.get("/hook", ...);
will respond to the URL /hook/hook.
I use express ejs on my backend and frontend. I have made a route to display the dashboard on the admin page. but I get 404 error to render view when I enter my url http: // localhost: 3000 /admin, here are some of my code:
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var admin = require('./routes/admin');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(indexRouter);
app.use('/admin', admin);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// app.use((req, res, next) => {
// res.status(404).render('error/404')
// });
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error/404');
});
module.exports = app;
controller dashboard.js
exports.getDashboard = (req, res, next) => {
res.render('dashboard', {
pageTitle: 'Dashboard',
path: 'admin/page/dashboard'
});
};
my admin route admin.js
const path = require('path');
var express = require('express');
const adminController = require('../controllers/backend/dashboard');
var router = express.Router();
/* GET users listing. */
router.get('/admin', adminController.getDashboard);
module.exports = router;
thank you, please help me for this issue
in app.js you already have route /admin then again in admin.js, so it will be accessible with localhost:3000/admin/admin.
Change your admin.js to
const path = require('path');
var express = require('express');
const adminController = require('../controllers/backend/dashboard');
var router = express.Router();
/* GET users listing. */
router.get('/', adminController.getDashboard);
module.exports = router;
The problem is here:
const adminController = require('../controllers/backend/dashboard');
You are not exporting a default option from controller dashboard so you need to add curly braces like this:
const { adminController } = require('../controllers/backend/dashboard');
Try this and let me know! :)
I've got a basic Node JS app (as I'm just learning). I'm using express, express-generator, express-myconnection, and mysql.
The issue has to do with querying the database connection itself.
The app is designed using an MVC structure.
Edit: to start off, here is my "app.js":
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
//var users = require('./routes/users');
var app = express();
var connection = require('express-myconnection');
var mysql = require('mysql');
app.use(
connection(mysql,{
"host":"localhost",
"user":"root",
"password":"root",
"port":3306,
"database":"fruits"
},'request')
);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
I have a model file, "fruits.js":
var fruits = function(data, req){
this.data = data;
this.req = req;
}
fruits.prototype.data = {};
fruits.prototype.getAll = function(callback){
this.req.getConnection(function(err, connection){
console.log(connection);
//var q = connection.query("SELECT * FROM `fruits`", function(err, rows){
//callback(rows);
//});
});
};
module.exports = fruits;
Then I also have a controller file (index.js):
var express = require('express');
var router = express.Router();
var fruits = require('../models/fruits.js');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/*GET fruits page */
router.get('/fruits',function(req, res, next){
var f = new fruits({}, req);
f.getAll(function(fruitsObj){
console.log(fruitsObj);
res.render('fruits',{
"title":"Fruits!",
"fruits":fruitsObj
});
});
});
module.exports = router;
What happens is whenever the fruits route is navigated to, I can't query the database. It says that the "connection" from "this.req.getConnection" is "undefined".
Is there any reason why I can't retrieve the database connection and query it based on the contents of these two files? I'm positive I have all my packages installed. I even ran npm install for all them again to make sure.
Thanks for your help in advance.
I'm following this tutorial: http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/
When I do db.usercollection.find().pretty() in my mongo terminal, my records print - so I know I have records to display.
When I do http://localhost:3000/userlist in my browser, I get the words "User List" at the top - but I don't get any of the user data.
It should look like this.
Question: Is my link in my userlist.jade file not pointing to the database data??
userlist.jade
extends layout
block content
h1.
User List
ul
each user, i in userlist
li
a(href="mailto:#{user.email}")= user.username
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/* GET Userlist page. */
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
module.exports = router;
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// new code
// we want to talk to mongodb, use monk to do it, databasebase is lcoated at localhost:27017/nodetest1
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Make our db accessible to our router - new code
app.use(function(req,res,next){
req.db = db;
next();
});
// telling Express what route files to use
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
// our master app exporting its app object. All modules export an object whch can easily be called elsewhere in code.
module.exports = app;
i was getting the same error and then i fixed the problem:
app.js
var db = monk('localhost:27017/nodetest1');
change the localhost to 127.0.0.1
and make sure the collection name is nodetest1
I am currently learning the MEAN stack by working my way through this tutorial. I have set up the node server and gotten mongodb successfully running however when i go to test the database via:
curl --data 'title=test&link=http://test.com' http://localhost:3000/posts
it gives me a 404 error. How ever if i just run curl on the address it sends back an empty container.
Currently my code looks like the following:
App.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
var users = require('./routes/users');
var mongoose = require('mongoose');
require('./models/Posts');
require('./models/Comments');
mongoose.connect('mongodb://localhost/Posts');
var routes = require('./routes/index');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
...
module.exports = app;
index.js
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Post = mongoose.model('Post');
var Comment = mongoose.model('Comment');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', {
title: 'Express'
});
});
router.get('/Posts', function(req, res, next) {
Post.find(function(err, posts) {
if (err) {
return next(err);
}
res.json(posts);
});
});
router.post('/Comments', function(req, res, next) {
var post = new Post(req.body);
post.save(function(err, post) {
if (err) {
return next(err);
}
res.json(post);
});
});
module.exports = router;
I feel like I have a fairly good grasp of javascript however i am stumped with why this isnt working. Thanks for the help, this is the first problem ive been completely stumped with