NodeJS and ExpressJS Router.use() error - javascript

I get this error:
TypeError: Router.use() requires middleware function but got a Object at Function. (C:/Users/peter/Desktop/mean/express-server/node_modules/express/lib/router/index.js:458:13)
I was testing my Api in post man and I got this error.
I got it when i in my app.js when I did app.use('/api',api);
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 session = require("express-session");
var routes = require('./routes/index');
var users = require('./routes/users');
var api = require('./routes/jokesApi');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(favicon(path.join(__dirname, 'public/images', '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(session({secret:'secret_3162735',saveUninitialized:true, resave: true}));
// The error comes from here
app.use('/api',api);
app.use(function (req, res, next) {
var session = req.session;
var input = req.body;
if(session.userName){
return next();
}else if(input.userName){
session.userName = input.userName;
return res.redirect('/');
}else{
req.url='/login';
return next();
}
});
app.use('/', routes);
app.use('/users', users);
module.exports = app;
JokesApi.js:
var express = require('express');
var jokes = require('../model/jokes');
var session = require("express-session")
var router = express.Router();
router.get('/joke/random',function(req,res,next){
res.end({joke: jokes.getRandomJoke()});
});
router.get('/jokes',function(req,res,next){
res.end({joke: jokes.allJokes});
});
router.post('/joke', function(req,res){
var funJoke = req.body;
var jsonJoke = funJoke.Joke;
jokes.addJoke(jsonJoke);
res.end({funnyNewJoke: jsonJoke});
})

You're not exporting your router in jokesApi.js. Add this to the end of that file:
module.exports = router;

The module jokesApi needs to be exported:
module.exports = router;
Try to follow this example: http://expressjs.com/en/guide/routing.html

Related

404 Not Found nodejs to localhost

I am writing nodejs express to fetch the data to web page. an error appear 404 Not Found when open
http://127.0.0.1:3000/users
in the Dev tool on the browser show: users:1 GET http://127.0.0.1:3000/users 404 (Not Found)
below are the app.js and index.js and users.js files
I think I have an issue with the routes
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 expressValidator = require('express-validator');
var flash = require('express-flash');
var session = require('express-session');
var bodyParser = require('body-parser');
var mysql = require('mssql');
// var connection = require('./lib/db');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
//I put false instead true
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: '123456cat',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}))
app.use(flash());
app.use(expressValidator());
app.use('/', indexRouter);
app.use('/list', usersRouter);
// 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;
below are the routes files.
routes/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;
routes/users.js
var express = require('express');
var router = express.Router();
var connection = require('../database.js');
/* GET home page. */
router.get('/', function(req, res, next) {
connection.query('SELECT * FROM users',function(err,rows) {
if(err){
req.flash('error', err);
res.render('list',{page_title:"Users - Node.js",data:''});
}else{
res.render('list',{page_title:"Users - Node.js",data:rows});
}
});
});
module.exports = router;
As I already mentioned in my comment, you don't have a /user route therefore you will get a 404 NotFound error.
Change this
app.use('/list', usersRouter);
To this
app.use('/user', usersRouter);

Express - get router.get to return json data attribute

I am new to javascript and would like to retrieve the json response from my express route get request. I can return the whole json but when i try to return a specific element i recieve an error (eg res.body.data). Here is my route file
route.js
var express = require('express');
var router = express.Router();
var request = require('request');
router.get('/', function(req, res, next) {
request({
uri: 'https://www.reddit.com/r/meme/new/.json'
}).pipe(res);
});
module.exports = router;
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 cors = require("cors");
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var testAPIRouter = require('./routes/testAPI');
var route = require('./routes/route');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/testAPI', testAPIRouter);
app.use('/route', route);
// 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;
You need to use body parser:
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));

login authentication not writing data in mongodb

I have a problem regarding my login/authentication node script. I believe the problem is that I don't even write in the mongodb, because when I check the db on mlab there's no data.
This is the app.js script in which the problem should be. The problem cannot be in signup.js or login.js as there would be an error alert.
Any help appreciated!
var express = require("express");
var path = require("path");
var favicon = require("static-favicon");
var logger = require("morgan");
var cookieParser = require("cookie-parser");
var bodyParser = require("body-parser");
var helmet = require("helmet");
var dbConfig = require("./db");
var mongoose = require("mongoose");
mongoose.connect(dbConfig.url);
var app = express();
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
app.use(helmet());
app.use(favicon());
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
//configuring passport
var passport = require("passport");
var expressSession = require("express-session");
app.use(expressSession({secret: "secretKey"}));
app.use(passport.initialize());
app.use(passport.session());
var flash = require("connect-flash");
app.use(flash());
var initPassport = require("./passport/init");
initPassport(passport);
var routes = require("./routes/index")(passport);
app.use("/", routes);
app.use(function(req,res,next) {
var err = new Error("Error Not found");
err.status = 404;
next(err);
});
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
});
});
}
module.exports = app;

Why is req.body always undefined for me

I cannot access any request parameters. e.g. req.body.username. for some reason req.body is always undefined. The endpoint is /youtube
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();
// 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');
});
module.exports = app;
server.js
var express = require("express");
var mysql = require('mysql');
var app = express();
var pool = mysql.createPool({
connectionLimit : 100, //important
host : 'localhost',
user : 'user',
password : 'pass',
database : 'db',
debug : false
});
var router = express.Router();// get an instance of the express Router
// middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Incoming request');
next(); // make sure we go to the next routes and don't stop here
});
app.get("/",function(req,res){-
handle_database(req,res);
});
router.route('/youtube')
.post(function(req, res) {
console.log(req.body); // always undefined
})
.get(function(req, res) {
});
app.use('/api', router);
app.listen(3000);
console.log("Listening on port 3000....")
Add those 3 lines right below var app = express(); in server.js:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Now your req.body will not be undefined.

Why my ejs is not rendering on redirecting?

I have made a form.On successful submission of the form I wanted to redirect my page to thankyou page(another ejs) view. Somehow if I am using res.redirect() it is not working but on using res.send('Thank you') it is working fine.
Below is the code of 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 mongoose = require('mongoose');
var routes = require('./routes/index');
var users = require('./routes/users');
var thankyou = require('./routes/thankyou');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
var engine = require('ejs-locals');
app.engine('ejs', engine);
app.set('view engine', 'ejs');
// 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')));
mongoose.connect('mongodb://localhost/my-data');
app.use('/', routes);
app.use('/users', users);
app.use('/thankyou', thankyou);
var Schema = new mongoose.Schema({
name : String,
email : String
});
var user = mongoose.model('Users', Schema);
app.post('/test',function(req,res){
new user({
email : req.body.email,
name : req.body.name
}).save(function(err, doc){
if(err){
console.log('boo');
}
else{
console.log('innner');
res.redirect("/thankyou");
res.end();
}
})
})
thankyou route:
var express = require('express');
var router = express.Router();
router.get('/thankyou', function(req, res) {
res.render('thankyou');
});
module.exports = router;
thankyou view
<h2>THANKS/h2>
This:
app.use('/thankyou', thankyou);
...combined with this:
router.get('/thankyou', ...);
...creates a route that matches /thankyou/thankyou.
Instead, you probably want this:
router.get('/', ...);

Categories

Resources