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
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'm having trouble with my node.js express routes. I'm really new to it and I can't see my mistake. I'm always getting a 404 Error when requesting localhost:2700/api/subs, but I think that my route is correct, isn't it? Can anybody see a mistake?
Beginning of the Error Message:
Error: Not Found
at ****/app.js:45:13
at Layer.handle [as handle_request] (****/node_modules/express/lib/router/layer.js:95:5)
Here is the 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');
const mongoose = require('mongoose');
// establish connection to the Database
mongoose.connect('mongodb://localhost/test', {
useMongoClient: true
});
mongoose.connection.once('open', function() {
console.log('Connection to Database has been established..');
}).on('error', function(error){
console.log(error);
});
var index = require('./routes/index');
var users = require('./routes/users');
Subscriber = require('./routes/subscriber.js');
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('/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 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');
});
app.get('/api/subs', function(req, res){
Subscriber.getSubscribers(function(err, subscribers){
if(err){
throw err;
}
res.json(subscribers);
});
});
// ... here is a function which creates the database objects and saves
// them. took it out for better overview....
app.listen(2700, function(){
console.log("Listening on Port 2700")
});
module.exports = app;
and the subscriber.js which is in the subdirectory ./routes:
const mongoose = require('mongoose');
var subscriberSchema = mongoose.Schema({
//seqnr shall go here. dunno how to declare integer x)
nr: Number,
name: String,
email: String,
uLink: String,
anwalt: String
});
var Subscriber = module.exports = mongoose.model('Subscriber', subscriberSchema);
//get Subscriber
module.exports.getSubscribers = function(callback, limit){
Subscriber.find(callback).limit(limit);
};
index.js
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;
You need to put your 404 app.use after all the other uses, otherwise it will ignore the api/subs after it.
Also, this bit will never run, because it also comes after an api.use that will always throw an error:
// 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');
});
Plus, you really shouldn't be throwing errors for 404s. It should tell the end user the page doesn't exist, but it shouldn't crash your script.
Also I agree with the other answer that says you should move those code blocks into separate router files, but that's more for good practice and structuring than for this particular bug.
Try putting it in a separate file and including it where you do with other routes, before the 404 handler
app.use('/', index);
app.use('/users', users);
So... make a subs.js route
var express = require('express');
var router = express.Router();
Subscriber = require('./routes/subscriber.js');
router.get('/', function(req, res){
Subscriber.getSubscribers(function(err, subscribers){
if(err){
throw err;
}
res.json(subscribers);
});
});
module.exports = router;
Then include it in your app.js
var subs= require('./routes/subs');
...
api.use('/api/subs', subs);
...
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
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 new to NodeJS and ExpressJS. I am following this tutorial http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/ for creating and connecting mongodb with nodejs. Everything works perfectly(DB data inserting through command line,package.json config) except db connection, it throws undefined error.
var monk = require('monk');
var db = monk('localhost:27017/deno');
I check this in console like this console.log(db) it shows 'undefined' in index.js
My app.js is :
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
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/Fujitsu');
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
app.use(function(req,res,next){
req.db = db;
next();
});
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: {}
});
});
module.exports = app;
routes/index.js is
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/************ Customized starts Here **********/
/* GET Userlist page. */
router.get('/userlist', function(req, res) {
var db = req.db;
console.log(db);
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
/******** Customized - Ends here ***********/
module.exports = router;
Please anyone of you tell me the solution because now I'm struggling with this.
Thanks In Advance.