Failed to pass value between middlewares - javascript

I got this in app.js
var routes = require('./routes/index');
app.use(function(req,res,next) {
res.something = 'something_value';
next();
}
});
app.use('/', routes);
Then I have a routes folder, it has index.js I do
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
console.log(req.something)
});
but I got undefined. What's wrong?
I also tried req.body.something, I got undefined too.

Related

Routing keeps returning 404 instead of displaying other views besides index, users, and error in Express.JS

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.

Cannot read property 'get' of undefined in Node.js

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');

Express subrouter returns 404

I have this router (http/api/ping.js):
var express = require('express');
var router = express.Router();
router.get('/ping', function (req, res) {
res.send("You called /api/ping");
});
module.exports = router;
This router is embedded into this router (http/api/index.js):
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.send('You called /api');
});
router.use('/ping', require('./ping'));
module.exports = router;
And this router is used by my Express.js app (app.js):
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var logger = require('./config').logger;
// Create app
var app = express();
var server = http.createServer(app)
var io = require('socket.io')(server);
// App config
app.use(bodyParser.json());
app.use('/api', require('./http/api'));
// Display requests on console
app.use(function (req, res, next) {
logger.trace(req.method, req._parsedUrl.href);
next()
});
module.exports = {
app: app,
server: server
};
When I run the app, /api returns You called /api, but /api/ping gives me a 404.
I am using Node 6.9.1 and Express ^4.14.0
I think order matters in this scenario. Try putting /ping above the / get route.
router.use('/ping', require('./ping'));
router.get('/', function (req, res) {
res.send('You called /api');
});
Also in your ping route you say the path to your route is /ping you also say it is /ping when you import it to the other router, which would make the path /api/ping/ping
change
router.get('/ping', function (req, res) {
res.send("You called /api/ping");
});
to
router.get('/', function (req, res) {
res.send("You called /api/ping");
});
I think your routing is incorrect on this line
router.use('/ping', require('./ping'));
this will point to http/api/ping/ping
it should be
router.use('/', require('./ping'));

Router.use requires middleware function?

So I'm trying to seperate my login routes in a seperate JS file called login_routes.js
I keep getting this specific error:
TypeError: Router.use() requires middleware function but got a Object
at Function. (/Users/ethanthomas/Desktop/mean-stuff/express-server/node_modules/express/lib/router/index.js:446:13)
Not entirely understanding what it's asking me to implement?
login_routes.js:
var express = require('express');
var app = express();
app.route('/login')
.get(function(req, res, next) {
res.send('this is the login form');
})
.post(function(req, res, next) {
console.log('processing');
res.send('proccessing the login form!');
});
server.js:
var express = require('express');
var app = express();
var path = require('path');
var adminRoutes = require('./app/routes/admin_routes');
var loginRoutes = require('./app/routes/login_routes');
app.use('/admin', adminRoutes);
app.use('/login', loginRoutes);
//send our index.html file to the user for the home page
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
//start the server
app.listen(1337);
console.log('leet is the magic port');
Your login_routes.js should look something like this (in the context of express):
var express = require('express');
var router = express.Router();
// GET request to /login
router.get('/', function(req, res, next) {
// do something
});
// POST request to /login
router.post('/', function(req, res, next) {
// do something
});
module.exports = router;
In your app.js you use
var login_routes = require('./login_routes');
...
app.use('/login', login_routes);
...
Have a look at the code generated by the express-generator module. That is a starting point for express webserver apps.
People have already offered hints at the solution in comments.
The first issue is that you need to export your "sub" app from login_routes.js. To do so, change this:
var app = express();
Into this:
var app = module.exports = express();
Secondly, you are—probably unintentionally—creating routes for GET /login/login and POST /login/login. To solve this, use this in login_routes.js:
app.route('/').get(...).post(...);
This is because the root path in your sub app (the one in login_routes.js) will get mapped to the path used in app.use() in your main app (server.js).
Do like this:
login_routes.js:
exports.get = function( req, res ) {
res.send('this is the login form');
};
exports.post = function( req, res ) {
console.log('processing');
res.send('proccessing the login form!');
};
server.js:
var loginRoutes = require('./app/routes/login_routes');
app.get('/login', loginRoutes.get);
app.put('/login', loginRoutes.post);
login_routes.js:
var express = require('express');
var app = express();
app.route('/login')
.get(function(req, res, next) {
res.send('this is the login form');
})
.post(function(req, res, next) {
console.log('processing');
res.send('proccessing the login form!');
});
module.exports = router;
just writ module.exports = router then it will be work

Route not found in node and express

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

Categories

Resources