Node/Express.js request handling with different files - node.js

//server.js
app.use('/shelf', require('./books').middleware);
//books.js
var app = new express.Router();
app.post('/books' , function (req, res) {
console.log('here');
});
module.exports = app;
This is what i did so far; my server runs under server.js, and when i make a '/shelf/books' request, it first goes to server.js and then to the books.js file and logs 'here'. but i want to add a request handler(a different file, handler.js i.e) where i want to to validate if the post param is a number and than redirect it to books.js if it is.

app.js
var express = require('express')
, http = require('http')
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(require('./handler').middleware);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
handler.js
var express = require('express')
var books = require('./books')
var router = new express.Router();
router.get('/shelf/:book_id', function(req, res){
var onlyNumbers =req.param('book_id').match(/^\d+$/)
if (onlyNumbers){
var parsedNumber = parseInt(req.param('book_id'));
if( parsedNumber ) {
books(parsedNumber)
console.log("Parsed number is : " + parsedNumber)
res.end("Parsed number is : " + parsedNumber)
}
}
else {
console.log("not a number : " + req.param('book_id'))
res.end("not a number : " + req.param('book_id'))
}
res.end('');
})
module.exports = router;
books.js
var express = require('express')
var app = new express.Router();
module.exports = function(req, res) {
console.log("\t in books module")
};

How about this?
//handler.js
module.exports = function (req, res, next) {
req.check_result = /\d+/.test(req.body.yourfield);
};
// book.js
app.post('/books' , function (req, res) {
if(req.check_result) {
// your code
} else {
// your code
}
});
// server.js
app.use('/shelf', require('./handler'));
app.use('/shelf', require('./books').middleware);

Related

Pass data from client to server. Express

i'm little stuck on my express application.
I have a file index.js in routes folder and I want to save the result of mydata
var express = require('express');
var router = express.Router();
router.get('/', token, function(req, res, next) {
var mydata = req.userId
res.render('index', {
title: 'Welcolme',
});
});
module.exports = router;
And, in my other file (which depends on app.js), I would like to get and pass mydata to the server
var app = require('../app');
server.listen(port, function () {
require('../assets/js/server/socket')(server, mydata);
});
(Here is my app.js)
var express = require('express');
var indexRouter = require('./routes/index');
var path = require('path');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'twig');
app.use('/', indexRouter);
module.exports = app;
And the socket file
var io = {};
module.exports = (server, mydata) => {
console.log('Hello : ' , mydata)
io = require('socket.io')(server);
io.on('connection', (socket) => {
console.log('Connected')
});
};
Is there a way to do that?
Thank you :)
Maybe instead of still having this route.get('/') ...
You can let the user enter the data and have it transferred directly through the WebSocket connection.
Example:
//Client-side
//Get the user data somewhere from the HTML page
const userData = document.getElementbyId("some html element's id here").innerHTML;
//Send it to the back end
socket.emit('userData',userData)
//Open a listener to get the data from the back end later
socket.on('processedData',processedData=>{
//Use it in the way you desired.
});
//Server-side
io.on('connection', (socket) => {
console.log('Connected')
socket.on('userData',userData=>{
//Do something here, like validation and stuff
socket.emit('processedData','processedData here')
});
});

404 Error Express Routing

I can't work out where I'm going wrong with this simple routing task. When I go to localhost:3030/staff, I'm getting "Cannot GET /staff" and a 404 error.
Here is my setup.
app.js:
const express = require('express');
const app = express();
const port = process.env.PORT || 3030;
const staffRouter = require('./routes/staffrouter.js');
app.use('/static', express.static(__dirname + './public'));
app.use('./staff', staffRouter);
app.get('/', function(req, res) {
res.render('index.pug');
});
app.listen(port);
I have tried using the paths "/staff" in my GET/POST requests, but that doesn't work, and isn't how it's supposed to work according to the tutorial I'm doing. I'm really stuck.
/routes/staffrouter.js:
var express = require('express');
var router = express.Router();
const staff = require('../staff').staff;
const urlEncoded = (express.urlencoded({ extended: true }));
router.get('/', function(req, res, next) {
res.render('staff.pug', {
deptOptions: staff.populateSelectors('department'),
posOptions: staff.populateSelectors('position'),
empArray: staff.readWriteJSON()
});
});
// Add new staff obj
router.post('/', urlEncoded, function(req, res, next) {
let sObj = req.body;
let dataArray = staff.readWriteJSON();
//console.log('data:', data);
dataArray.push(new staff.Employee(
sObj.fName,
sObj.lName,
sObj.staffNum,
sObj.department,
sObj.position,
sObj.email,
sObj.phone
));
staff.readWriteJSON(dataArray)
res.render('../views/staff.pug', {
deptOptions: staff.populateSelectors('department'),
posOptions: staff.populateSelectors('position'),
empArray: staff.readWriteJSON()
});
});
module.exports = router;
wrong scope change the order
app.use('/static', express.static(__dirname + './public'));
const staffRouter = require('./routes/staffrouter.js');

Express router not working

I'm new to express and used yo-generator to create my project. The problem I'm facing is that routes with:
app.get('/something') are working fine, but
router.get('/something') are not working. I tried to research but could not solve the problem.
Here are my files:
app.js
var fs = require('fs');
var http = require('http');
var path = require('path');
var helmet = require('helmet');
var express = require('express');
var root = path.normalize(__dirname + '/');
var constant = require(root + '/app/util/constants.js');
var config = require(constant.APP_CONFIG_FILE);
var app = express();
app.use(helmet());
app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type");
return next();
});
require('./config/express')(app, config);
http.createServer(app).listen(config.WEB_PORT, function() {
console.log('Server listening http on port ' + config.WEB_PORT);
});
module.exports = app;
Lines from express.js
var env = process.env.NODE_ENV || 'development';
app.locals.ENV = env;
app.locals.ENV_DEVELOPMENT = env == 'development';
app.set('views', config.ROOT + '/app/views');
app.set('view engine', 'ejs');
// app.use(favicon(config.root + '/public/img/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(compress());
app.use(express.static(config.ROOT + '/public'));
app.use(methodOverride());
var controllers = glob.sync(config.ROOT + '/app/controllers/*.js');
controllers.forEach(function(controller) {
require(controller)(app);
});
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app/controllers/user-ctrl.js
var path = require('path');
var express = require('express');
var router = express.Router();
var root = path.normalize(__dirname + '/../..');
var constant = require(root + '/app/util/constants.js');
var service = require(constant.USER_SERVICE_FILE);
var responseUtil = require(constant.RESPONSE_UTIL_FILE);
module.exports = function(app) {
app.use(constant.USER_PATH, router); // constant.USER_PATH is '/user' (added after alexmac asked)
**// this works**
app.get('/test', function(req, res) {
res.write('hello');
res.end();
});
**// This doesn't work**
router.get('/test', function(req, res) {
res.write('hello');
res.end();
});
};
/*
GET: /user
*/
router.route('/:page?/limit?/:limit')
.get(function(req, res) {
responseUtil.sendResponse(service.allRecords(req, res), req, res);
});
/*
POST: /user
*/
router.route('/')
.post(function(req, res) {
responseUtil.sendResponse(service.saveRecord(req, res), req, res);
});
/*
GET: /user/1
PUT: /user/1
DELETE: /user/1
*/
router.route('/:id')
.get(function(req, res) {
responseUtil.sendResponse(service.findRecord(req, res), req, res);
})
.delete(function(req, res) {
responseUtil.sendResponse(service.deleteRecord(req, res), req, res);
})
.put(function(req, res) {
responseUtil.sendResponse(service.updateRecord(req, res), req, res);
});
These are the key lines. I've changed the order to try to clarify the intent but that shouldn't change how they behave:
// Create a route for GET /test
app.get('/test', function(req, res) {
res.write('hello');
res.end();
});
// Create a route for GET /user/test
router.get('/test', function(req, res) {
res.write('hello');
res.end();
});
app.use('/user', router);
The router is mounted at the path /user so any paths on the router will be relative to /user. In other words, if app is handling requests at http://localhost/test then router will handle http://localhost/user/test.
Change your code with this piece of code
var express = require('express');
var bodyParser = require('body-parser');
var router = express.Router();
router.use(bodyParser.json());
var app = express();
router.get('/test', function(req, res) {
res.write('hello');
res.end();
});
app.use('/route',router);
module.exports = router;
When you want to get use http://localhost:port/route/test
Hope this helps.

Unable to post on nodejs in heroku

I have a nodejs app running on Heroku. Here is the server.js file
var express = require('express')
, cors = require('cors')
, app = express();
var http = require('http').Server(app);
var io = require("socket.io").listen(http);
app.use(cors());
require('./modules/routes.js')(app,io);
app.set('port', process.env.PORT || 5000);
app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
Here is my routes.js
"use strict";
const bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var time = require('express-timestamp');
var Promise = require('promise');
var momentjs = require('moment');
var _ = require('lodash');
var method = routes.prototype;
function routes(app, io) {
app.use(time.init);
app.use(cookieParser());
app.use(session({ secret: 'asdo8rter65edfgfd53wet34634632y4bluaq', resave: true, saveUninitialized: true }));
app.all('/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.use(bodyParser.json());
app.post('/testHeroku', function(req, res) {
console.log(req);
res.write(JSON.stringify({
process: "success"
}));
res.end();
});
}
method.getroutes = function() {
return this;
}
module.exports = routes;
I'm trying to access /testHeroku from an ionic app running in android emulator.
Ionic code:
vm.testHeroku = function(){
console.log('testing heroku');
var testdata = {
url: config.baseURL + 'testHeroku',
dataServer: {
serverTaskRequest: 'getUADSF'
}
}
runajax.runajax_function(testdata, function (testdataResponse) {
if (testdataResponse.process == 'success') {
alert(testdataResponse.process);
}
});
};
Here goes my config.baseURL = abcd-1234.herokuapp.com (This is example for the heroku app url)
I don't receive any return form the http call.
Code for run_ajax service
.service('runajax', ['$http', function ($http) {
this.runajax_function = function (request, callback) {
var url = request.url;
var dataServer = request.dataServer;
// console.log('runajax function called -> ' + url);
// console.log(dataServer);
$http.post(url, dataServer).success(function (data, status, headers, config) {
callback(data);
})
.error(function () {
callback(status);
});
}
}])
I got it working. There was an error with app.set('port', process.env.PORT || 5000); I changed it to var port = process.env.PORT || 8080;

Multiple request url mapping handler in one controller does not work in Node Express JS

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"

Resources