I am calling the config file from server.js. when i call the config file, I am getting the error as ReferenceError: bodyparser is not defined. I don't understand the wrong with my end.
any one help me to sort this?
here is my config file :
var
path = require('path'),
routes = require('./routes'),
exphbs = require('express-handlebars'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
morgan = require('morgan'),
methodOverride = require('method-override'),
errorHandler = require('errorhandler');
module.exports = function(app) {
app.use(morgan('dev'));
app.use(bodyParser({
uploadDir:path.join(__dirname, 'public/upload/temp')
}));
app.use(methodOverride());
app.use(cookieParser('some-secret-value-here'));
routes(app);
app.use('/public/', express.static(path.join(__dirname, '../public')));
if ('development' === app.get('env')) {
app.use(errorHandler());
}
return app;
};
server.js:
var express = require('express'),
config = require('./server/configure'),
app = express();
app
.set( "port", process.env.PORT || 3300 );
app
.set( "views", __dirname + '/views');
app = config( app );
// app
// .get('/', function( req, res ) {
// res.send( 'Hello World' );
// } );
app
.listen( app.get('port'), function () {
console.log('Server up: http://localhost:' + app.get('port'));
})
update
module.exports = function(app) {
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser({
uploadDir:path.join(__dirname, 'public/upload/temp')
}));
app.use(methodOverride());
app.use(cookieParser('some-secret-value-here'));
routes(app);
app.use('/public/', express.static(path.join(__dirname, '../public')));
if ('development' === app.get('env')) {
app.use(errorHandler());
}
return app;
};
Add following inside function in config.js
// parse application/json
app.use(bodyParser.json());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse the raw data
app.use(bodyParser.raw());
// parse text
app.use(bodyParser.text());
Reference to bodyParser documentation
Updated code:
In configure.js
var path = require('path'),
express = require('express'),
bodyParser = require('body-parser');
module.exports = function(app) {
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser({
uploadDir:path.join(__dirname, 'public/upload/temp')
}));
return app;
};
In server.js
var express = require('express'),
config = require('./configure'),
app = express();
bodyParser = require('body-parser');
app = config( app );
app.post('/about', function( req, res ) {
console.log(req.body.message);
res.send( 'Hello World' );
});
app.listen( 3000, function () {
console.log('Server up: http://localhost:' + 3000);
});
TypeError: Cannot read property 'Store' of undefined
at new module.exports (/home/dickens/Desktop/node-login/node_modules/connect-mongo/src/index.js:58:50)
at Object. (/home/dickens/Desktop/node-login/app.js:56:14)
change directory of your index.js in the (/home/user/your-app/node_modules/connect-mongo/src/index.js:58:50)
Related
I know that I am connecting to 'routes/dropbox' When I call the post inside the router, I get the error "Route.post() requires a callback function but got a [object Object]"
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 helmet = require('helmet');
var cors = require('cors');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var authRouter = require('./routes/auth');
var dbRouter = require('./routes/dropbox');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('combined'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(helmet());
app.use(cors());
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/auth', authRouter);
app.use('/db', dbRouter);
dropbox.js
You can see that I my app.post is set up inside router. The error is occurring when I call that post. Did I write this incorrectly?
var express = require('express');
var router = express.Router();
const dotenv = require('dotenv');
dotenv.config();
var app = express();
router.get('/getAllFolders', function (request, response, next)
{
app.post('https://api.dropboxapi.com/2/files/list_folder',
{
headers:
{
'Content-Type' : 'application/json',
'Authorization' : process.env.DB_AUTH
},
data:
{
'path': '',
'recursive': false,
'include_media_info': false,
'include_deleted': false,
'include_has_explicit_shared_members': false,
'include_mounted_folders': true,
'include_non_downloadable_files': false
}
})
.then(function (r)
{
res.send(r);
})
.catch(function (e)
{
res.send(e);
});
});
module.exports = router;
app is a local express instance. app.post is setting up a local handler for a post request, similar to router.post would.
Use a http client library like axios.
const axios = require('axios');
axios.post('https://api.dropboxapi.com/2/files/list_folder', data, options)
.then(function (r) {
res.send(r);
})
.catch(function (error) {
res.status(500);
res.send(error);
});
I have my backend in NodeJs and front-end in angular2+. I am getting this error when i run my server.js file in Terminal using the command
nodemon server.js
Error -
throw new TypeError('Router.use() requires a middleware function but
got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a
Object
And it points out to this line -
app.use('/login', require('./api-mine-server/controller/login-
controller'));
I checked many posts on stackoverflow with the same error and i tried a few but i don't get the output. I haven;t implemented token yet
server.js
// Server definitions
require('rootpath')();
var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
const neo4j = require('neo4j-driver').v1;
var restify = require('restify');
var expressJwt = require('express-jwt');
var session = require('express-session');
var config = require('./config.json')
var app = express();
var router = express.Router();
module.exports = router;
var port = 3003;
app.use(restify.plugins.bodyParser());
app.use(bodyParser.urlencoded({ extended: false }));
// app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
app.use(cors());
//Express Token
app.use(session({ secret: config.secret, resave: false, saveUninitialized: true }));
// use Express-JWT auth to secure the api, the token can be passed in the authorization header or querystring.
app.use(expressJwt({
secret: config.secret,
getToken: function (req) {
console.log("####### ", req.headers)
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
return req.headers.authorization.split(' ')[1];
} else if (req.query && req.query.token) {
return req.query.token;
}
return null;
}
})
);
// ----------------- File Uploader code -------------------------
// var express = require('express');
var multer = require('multer');
var path = require('path');
var app = express();
var mkdirp = require('mkdirp')
var port = 3003;
// var fileNameController = require('./api-mine-server/api-mine-controller');
// File Upload YAML and WSDL
var myModuleYaml = require('./api-mine-server/controller/api-mine-yaml-controller');
var myModuleWsdl = require ('./api-mine-server/wsdl-server/api-mine-wsdl-controller.js')
// specify the folder
app.use(express.static(path.join(__dirname, 'uploads'))); //uncomment it
// // headers and content type
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); //uncomment it
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var storage = multer.diskStorage({
destination: function (req, file, cb) {
// console.log("im in storage");
// var dir = './uploads/'+req.dataProviderId+'/'+req.consentId;
var dir = './uploads/';
mkdirp(dir, function (err) {
if (err) {
console.error(err);
}
// move cb to here
cb(null, dir);
});
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
var upload = multer({ storage: storage });
app.post("/upload", upload.array("uploads[]", 12), function (req, res) {
console.log("request = ", req)
fileName = req.files[0].path;
serverOrganisation = req.body.uploads[0];
serverDepartment = req.body.uploads[1];
serverSystem = req.body.uploads[2];
console.log("organisation =", serverOrganisation , " department = ",serverDepartment, " system = ", serverSystem)
var lastFive = fileName.substr(fileName.length - 5);
console.log( lastFive);
console.log("Filename.extension = lastFive letters = ", lastFive)
if(lastFive == ".yaml"){
myModuleYaml.defineRoutes(router, fileName);
console.log("global variable FileName = ", fileName)
}
if (lastFive == ".wsdl"){
myModuleWsdl.defineRoutes(router,fileName,serverOrganisation,serverDepartment,serverSystem)
console.log("global variable FileName = ", fileName)
}
console.log('files', req.files);
console.log("request filename = ", req.files[0].filename);
console.log("request file path = ", req.files[0].path);
res.send(req.files);
});
//reason for removal of undefined
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true }));
// app.use(app.router);
// routes.initialize(app);
app.use('/seekOrganization', require('./api-mine-server/controller/seekOrganization-controller'));
app.use('/deleteAll', require('./api-mine-server/controller/deleteAll-controller'));
app.use('/deleteRelationships', require('./api-mine-server/controller/deleteRelationships-controller'));
app.use('/seekExtraction', require('./api-mine-server/controller/seekExtraction-controller'));
app.use('/seekIntersection', require('./api-mine-server/controller/seekIntersection-controller'))
app.use('/seekParentNodeCount', require('./api-mine-server/controller/seekParentNodeCount-controller'))
app.use('/seekAccurateParentNodeCount', require('./api-mine-server/controller/seekAccurateParentNodeCount-controller'));
app.use('/seekAccurateExtraction', require('./api-mine-server/controller/seekAccurateExtraction-controller'));
//------- server.js variables -------------------
//var cors = require('cors');
var fs = require('fs');
var path = require('path');
var compression = require('compression');
var morgan = require('morgan');
var app = express();
var router = express.Router();
app.use(compression());
app.use(cors());
//reason for removal of undefined
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true }));
//login and registration
app.use('/register', require('./api-mine-server/controller/register-controller'));
app.use('/login', require('./api-mine-server/controller/login-controller'));
var port = 3003;
var server = app.listen(process.env.PORT || port, function() {
console.log('Server listening at http://' + server.address().address + ':' + server.address().port);
});
In my server.js file I have below url mappings:
app.use('/registerCourse', require('./controllers/training.controller'));
app.use('/getCourses', require('./controllers/training.controller'));
In training.controller file I have mapped below way:
router.post('/registerCourse', registerCourse);
router.get('/getCourses', getCourses);
when call "/registerCourse","/getCourses","/getCourseDetails" throwing error saying:
"Cannot GET /getCourses"
Server.js -
require('rootpath')();
var express = require('express');
var app = express();
var session = require('express-session');
var bodyParser = require('body-parser');
var expressJwt = require('express-jwt');
var config = require('config.json');
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(session({ secret: config.secret, resave: false, saveUninitialized: true }));
app.use('/login', require('./controllers/login.controller'));
app.use('/app', require('./controllers/app.controller'));
app.use('/registerCourse', require('./controllers/training.controller'));
app.use('/getCourses', require('./controllers/training.controller'));
app.use('/getCourseDetails', require('./controllers/training.controller'));
app.get('/', function (req, res) {
return res.redirect('/app');
});
var server = app.listen(3000, function () {
console.log('Server listening at http://' + server.address().address + ':' + server.address().port);
});
training.controller.js-
var config = require('config.json');
var express = require('express');
var app = express();
var router = express.Router();
var trainingService = require('services/training.service');
app.use(router);
router.post('/registerCourse', registerCourse);
router.get('/getCourses', getCourses);
router.get('/getCourseDetails', getCourseDetails);
module.exports = router;
function registerCourse(req, res) {
console.log(" registerCourse called ()"+req.body);
trainingService.register(req.body);
}
function getCourses(req, res) {
trainingService.getCourses()
.then(function (data) {
res.json(data);
})
.catch(function (err) {
res.status(400).send(err);
});
}
function getCourseDetails(req, res) {
console.log(req.body)
}
Solution:
Your route will be:
/registerCourse
/getCourses
/getCourseDetails
app.js
app.use('/login', require('./controllers/login.controller'));
app.use('/app', require('./controllers/app.controller'));
app.use('/',require('./controllers/training.controller'));
/*
app.use('/registerCourse', require('./controllers/training.controller'));
app.use('/getCourses', require('./controllers/training.controller'));
app.use('/getCourseDetails', require('./controllers/training.controller'));
-- removed
*/
training.controller.js
var config = require('config.json');
var express = require('express');
// var app = express(); -- removed
var router = express.Router();
var trainingService = require('services/training.service');
// app.use(router); -- removed
router.post('/registerCourse', registerCourse);
router.get('/getCourses', getCourses);
router.get('/getCourseDetails', getCourseDetails);
module.exports = router;
function registerCourse(req, res) {
console.log(" registerCourse called ()"+req.body);
trainingService.register(req.body);
}
function getCourses(req, res) {
trainingService.getCourses()
.then(function (data) {
res.json(data);
})
.catch(function (err) {
res.status(400).send(err);
});
}
function getCourseDetails(req, res) {
console.log(req.body)
}
In server.js you can use
app.use('/', require('./controllers/training.controller'));
app.use('/', require('./controllers/training.controller'));
app.use('/', require('./controllers/training.controller'));
and then try calling your
"/registerCourse","/getCourses","/getCourseDetails"
In my understanding, the way to serve views is to do the following:
app.set('view engine', 'ejs'); // or jade or whatever
app.set('views', __dirname + '/views'); // specify where to find the view files e.g. index.ejs
app.get("/", function(req, res) { res.render('index') });
However, when I check the code here https://github.com/jedireza/drywall/ , which is a boilerplate for node user management, I don't see any routes defined in app.js. But it works fine and if I type the url /signup in browser it will render signup.jade.
Which part, or which middleware is doing the magic of routing?
app.js content:
'use strict';
//dependencies
var config = require('./config'),
express = require('express'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
session = require('express-session'),
mongoStore = require('connect-mongo')(session),
http = require('http'),
path = require('path'),
passport = require('passport'),
mongoose = require('mongoose'),
helmet = require('helmet'),
csrf = require('csurf');
//create express app
var app = express();
//keep reference to config
app.config = config;
//setup the web server
app.server = http.createServer(app);
//setup mongoose
app.db = mongoose.createConnection(config.mongodb.uri);
app.db.on('error', console.error.bind(console, 'mongoose connection error: '));
app.db.once('open', function () {
//and... we have a data store
});
//config data models
require('./models')(app, mongoose);
//settings
app.disable('x-powered-by');
app.set('port', config.port);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
//middleware
app.use(require('morgan')('dev'));
app.use(require('compression')());
app.use(require('serve-static')(path.join(__dirname, 'public')));
app.use(require('method-override')());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser(config.cryptoKey));
app.use(session({
resave: true,
saveUninitialized: true,
secret: config.cryptoKey,
store: new mongoStore({ url: config.mongodb.uri })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(csrf({ cookie: { signed: true } }));
helmet(app);
//response locals
app.use(function(req, res, next) {
res.cookie('_csrfToken', req.csrfToken());
res.locals.user = {};
res.locals.user.defaultReturnUrl = req.user && req.user.defaultReturnUrl();
res.locals.user.username = req.user && req.user.username;
next();
});
//global locals
app.locals.projectName = app.config.projectName;
app.locals.copyrightYear = new Date().getFullYear();
app.locals.copyrightName = app.config.companyName;
app.locals.cacheBreaker = 'br34k-01';
//setup passport
require('./passport')(app, passport);
//setup routes
require('./routes')(app, passport);
//custom (friendly) error handler
app.use(require('./views/http/index').http500);
//setup utilities
app.utility = {};
app.utility.sendmail = require('./util/sendmail');
app.utility.slugify = require('./util/slugify');
app.utility.workflow = require('./util/workflow');
//listen up
app.server.listen(app.config.port, function(){
//and... we're live
});
The routes are being added here:
//setup routes
require('./routes')(app, passport);
I just moved to express.js 4.8.7 from 3.x.
I am getting error in express 4.x, "req.body" is undefined.
When I google it. I found that, I have to install "body-parser' module. Even after installing "body-parser' module, I am getting "req.body" undefined.
I am not sure what I need to do. Below is my app.js code
var express = require('express')
, path = require('path')
, redis = require("redis")
, mongoose = require('mongoose')
, favicon = require('serve-favicon')
, compression = require('compression')
, bodyParser = require('body-parser')
, methodOverride = require('method-override')
, errorHandler = require('errorhandler')
, cookieParser = require('cookie-parser')
, morgan = require('morgan')
, multer = require('multer')
, session = require('express-session');
var app = express();
var router = express.Router();
router.use(function(req, res, next) {
console.log('%s %s %s', req.method, req.url, req.path);
next();
});
var routes = require('./routes')(app);
mongoose.connect('mongodb://localhost/abc');
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(favicon(__dirname + '/public/img/favicon.ico'));
app.use(morgan('dev'));
app.use(methodOverride());
app.use(session({resave: true, saveUninitialized: true, secret: 'uwotm8'}));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(multer({ dest: './uploads/'}));
app.use(methodOverride('X-HTTP-Method'));
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(methodOverride('X-Method-Override'));
app.use(compression({'threshold': 512}));
app.use(express.static(path.join(__dirname, 'public')));
if ('development' == app.get('env')) {
app.use(errorHandler());
}
app.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Error happends in my router callback function.
app.route('/xhr/abc').post(function (req, res) {
if (req.xhr) {
var language = req.headers["accept-language"];
...
var reqBody = req.body;
...
}
You need to make sure that your routes come after your included middleware, since middleware/routes/etc. are executed in order in Express 4.