Node module named dishRouter.js implements the Express router for the /dishes/:dishId REST API endpoint.
index.js
const express = require('express');
const http = require('http');
const morgan = require('morgan');
const hostname = 'localhost';
const port = 3000;
const app = express();
const dishRouter = require('./routes/dishRouter');
const bodyParser = require('body-parser');
app.use(morgan('dev'));
app.use(bodyParser.json()); //parse the json in the body
app.use('/dishes/:dishId', dishRouter);
app.use(express.static(__dirname + '/public'));
app.use((req, res, next) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end('<html><body><h1>This is an express server</h1></body></html');
});
const server = http.createServer(app);
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}`)
});
dishRouter.js
const express = require('express');
const bodyParser = require('body-parser');
const dishRouter = express.Router();
dishRouter.use(bodyParser.json());
dishRouter.route('/')
.all((req, res, next) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
next();
})
.get((req, res, next) => {
res.end('Will send details of the dish: ' + req.params.dishId + ' to you!');
})
.post((req, res, next) => {
res.write('Updating the dish: ' + req.params.dishId + '\n');
res.end('Will update the dish: ' + req.body.name +
' with details: ' + req.body.description);
})
.put((req, res, next) => {
res.end(req.params.dishId + ' Will update the dishId and dish: ' + req.body.name + 'with details: ' + req.body.description);
})
.delete((req, res, next) => {
res.end('Deleting the dishId: ' + req.params.dishId);
});
module.exports = dishRouter;
When sending a GET request to localhost:3000/dishes/28, the following response is sent:
Will send details of the dish: undefined to you!
But what I need is Will send details of the dish:28 to you!, and I am unable to solve the problem.
I also need the same response for the other method calls.
When you store your Router in dishRouter, you need to tell it to inherit params from parents.
...
const dishRouter = express.Router({ mergeParams: true });
...
Express document
When I visit mysite.com/verify/myusn the result is a 404 error. When I visit mysite.com/ it serves me the index page as expected.
When I turned on the debugger, I realized Express was trying to serve a static file instead. But it also shows my route being registered properly. Please help me out.
Here is my debugger:
Here is my server.js:
var express = require('express');
var app = express();
var path = require('path');
app.get('/*', function(req, res, next){
next();
});
app.use(express.static(path.join(__dirname , '/_site/') , {maxAge:0}));
app.use('/assets/', express.static(path.join(__dirname , '/_site/assets') , {maxAge:0}));
var routesLogin = require(path.join(__dirname, '/api/routes/users'));
routesLogin(app);
app.get('/', function(req, res) {
res.sendFile( path.join(__dirname , '/_site/landing.html'));
});
app.get('*', function(req, res) {
res.send('404');
});
app.post('*', function(req, res) {
res.send('404');
});
port = process.env.PORT || 3000;
app.listen(port);
console.log('listening on ' + port);
./api/routes/users.js:
module.exports = function(app){
var users = require('../controllers/userController');
app.route('verify/:usn')
.get(users.verifyUSN)
};
./api/controllers/userController.js:
exports.verifyUSN = function(req, res, next){
res.status(200)
.json({
status: 'success',
data: data,
message: 'USN Verified.'
});
}
I believe your problem could potentially be in /api/routes/users.js
module.exports = function(app){
var users = require('../controllers/userController');
// previously app.route('verify/:usn')
app.route('/verify/:usn')
.get(users.verifyUSN)
};
Hope this helps.
when I add all three files (dishRouter.js, promoRouter.js and leaderRouter.js in app.js) shows me the following error
error image
This 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 routes = require('./routes/index');
var users = require('./routes/users');
var dishRouter = require('./routes/dishRouter');
var promoRouter = require('./routes/promoRouter');
var leaderRouter = require('./routes/leaderRouter');
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('/', routes);
app.use('/users', users);
app.use('/dishes',dishRouter);
app.use('/promotions',promoRouter);
app.use('/leadership',leaderRouter);
// 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;
This is dishRouter.js
var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var hostname = 'localhost';
var port = 3000;
var app = express();
app.use(morgan('dev'));
var dishRouter = express.Router();
dishRouter.use(bodyParser.json());
dishRouter.route('/')
.all(function(req,res,next) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
next();
})
.get(function(req,res,next){
res.end('Will send all the dishes to you!');
})
.post(function(req, res, next){
res.end('Will add the dish: ' + req.body.name + ' with details: ' + req.body.description);
})
.delete(function(req, res, next){
res.end('Deleting all dishes');
});
dishRouter.route('/:dishId')
.all(function(req,res,next) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
next();
})
.get(function(req,res,next){
res.end('Will send details of the dish: ' + req.params.dishId +' to you!');
})
.put(function(req, res, next){
res.write('Updating the dish: ' + req.params.dishId + '\n');
res.end('Will update the dish: ' + req.body.name +
' with details: ' + req.body.description);
})
.delete(function(req, res, next){
res.end('Deleting dish: ' + req.params.dishId);
});
app.use('/dishes',dishRouter);
app.use(express.static(__dirname + '/public'));
app.listen(port, hostname, function(){
console.log(`Server running at http://${hostname}:${port}/`);
});
module.exports = dishRouter;
this is leaderRouter.js
var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var hostname = 'localhost';
var port = 3000;
var app = express();
app.use(morgan('dev'));
var leaderRouter = express.Router();
leaderRouter.use(bodyParser.json());
leaderRouter.route('/')
.all(function(req,res,next) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
next();
})
.get(function(req,res,next){
res.end('Will send all the leaders to you!');
})
.post(function(req, res, next){
res.end('Will add the leader: ' + req.body.name + ' with details: ' + req.body.description);
})
.delete(function(req, res, next){
res.end('Deleting all leaders');
});
leaderRouter.route('/:leaderId')
.all(function(req,res,next) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
next();
})
.get(function(req,res,next){
res.end('Will send details of the leader: ' + req.params.leaderId +' to you!');
})
.put(function(req, res, next){
res.write('Updating the leader: ' + req.params.leaderId + '\n');
res.end('Will update the leader: ' + req.body.name +
' with details: ' + req.body.description);
})
.delete(function(req, res, next){
res.end('Deleting leader: ' + req.params.leaderId);
});
app.use('/leaders',leaderRouter);
app.use(express.static(__dirname + '/public'));
app.listen(port, hostname, function(){
console.log(`Server running at http://${hostname}:${port}/`);
});
module.exports = leaderRouter;
and this is promoRouter.js
var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var hostname = 'localhost';
var port = 3000;
var app = express();
app.use(morgan('dev'));
var promoRouter = express.Router();
promoRouter.use(bodyParser.json());
promoRouter.route('/')
.all(function(req,res,next) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
next();
})
.get(function(req,res,next){
res.end('Will send all the promotions to you!');
})
.post(function(req, res, next){
res.end('Will add the promotion: ' + req.body.name + ' with details: ' + req.body.description);
})
.delete(function(req, res, next){
res.end('Deleting all promotions');
});
promoRouter.route('/:promotionId')
.all(function(req,res,next) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
next();
})
.get(function(req,res,next){
res.end('Will send details of the promotion: ' + req.params.promotionId +' to you!');
})
.put(function(req, res, next){
res.write('Updating the promotion: ' + req.params.promotionId + '\n');
res.end('Will update the promotion: ' + req.body.name +
' with details: ' + req.body.description);
})
.delete(function(req, res, next){
res.end('Deleting promotion: ' + req.params.promotionId);
});
app.use('/promotions',promoRouter);
app.use(express.static(__dirname + '/public'));
app.listen(port, hostname, function(){
console.log(`Server running at http://${hostname}:${port}/`);
});
module.exports = promoRouter;
but to add only one router, works perfectly, why?
I use Win7, node v4.4.5, npm v3.9.0
In each router you're calling app.listen. This is what starts the express server listening on that port. It will work for the first router, but on the second it will throw an error telling you that the port is in use. Only one application can listen on a specific port. The correct way to do this is to remove anything common from the individual routers and put them in your app.js
Right deleting app.listen() makes server run successfully. But requests for the routing scripts are responded by 404 message by the server with the code.
tried the following routing codes in link below
https://gist.github.com/MCheli/c4efc94f0d754f3e497e13b1bbf04b0d
and server code below
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 routes = require('./routes/index');
var users = require('./routes/users');
var dishRouter = require('./routes/dishRouter');
var promoRouter = require('./routes/promoRouter');
var leaderRouter = require('./routes/leaderRouter');
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('/', routes);
app.use('/users', users);
app.use('/dishes',dishRouter);
app.use('/promotions',promoRouter);
app.use('/leadership',leaderRouter);
// 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 userfor the server.js file
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
i can't access to my express application's home page by '/' route pattern. it's working on /index e.g. My express version is 4.6.
I tried app.use('/*', router), but my application is not responding or 503 service temporarily unavailable. It's now working by '/index' pattern and other routes is working correctly. only '/' pattern is not working. :)
Here is my code snippet.
var http = require('http');
var express = require('express');
var app = express();
var router = express.Router();
app.use('/', router);
app.set('view engine', 'ejs');
app.set('views', './views');
app.use(express.static('./public'));
var bodyParser = require("body-parser");
app.use(bodyParser());
var fs = require('fs');
var clientSessions = require("client-sessions");
var form = require('express-form');
var field = form.field;
var sha1 = require('sha1');
var mysql = require('mysql');
var connection = mysql.createConnection({
host: process.env.OPENSHIFT_MYSQL_DB_HOST,
port: process.env.OPENSHIFT_MYSQL_DB_PORT,
user: process.env.OPENSHIFT_MYSQL_DB_USERNAME,
password: process.env.OPENSHIFT_MYSQL_DB_PASSWORD,
database: process.env.OPENSHIFT_GEAR_NAME
});
var multer = require('multer');
var done = false;
app.use(clientSessions({
secret: 'xxxxx'
}));
app.use(function(req, res) {
res.status(400);
res.render('pages/404');
});
// Handle 500
app.use(function(error, req, res, next) {
res.status(500);
res.render('pages/500');
});
//---
app.use(multer({
dest: 'public/uploads/',
rename: function(fieldname, filename) {
return filename + Date.now();
},
onFileUploadStart: function(file) {
console.log(file.originalname + ' is starting ...')
},
onFileUploadComplete: function(file) {
console.log(file.fieldname + ' uploaded to ' + file.path)
done = true;
}
}));
//// --------------- start app routes --------------//
// ----- GET -----
router.get('/', function() { // THIS PATTERN IS NOT WORKING
console.log('hello world'); // this line is not working
connection.query(strQuery, function(err, rows) {
// res.render('pages/index');
});
});
Because you didn't handle "/", here is updated code
var router = express.Router();
app.use('/*', router);
router.get('/', function(req, res) {
res.send('welcome home');
}
router.get('/index', function(req, res) {
res.send('welcome index');
}
You are forgetting '*' in second line
app.use('/*', router);
Do you forget to make redirection?
router.get("/", function (req, res) {
res.redirect("/index");
});
I'm using the code below to learn a bit about the new express.js (4.0). I can't seem to understand why the logging is happening regardless of which path I hit with my browser. Shouldn't it only log for website.get and not for api.get paths?
// Express 4.0 test...
var express = require('express');
var app = express();
var website = express.Router();
var api = express.Router();
var port = process.env.PORT || 3000;
website.use(function (req, res, next) {
console.log(req.method, req.url);
next();
});
website.get('/', function (req, res) {
res.send('Home page');
});
website.get('/about', function (req, res) {
res.send('About page');
});
api.get('/', function (req, res) {
res.send({'json':'response'});
});
api.get('/user', function (req, res) {
res.send({'user':'john'});
});
// app.get('/', function (request, response) {
// response.writeHead(200, {"Content-Type": "text/html"});
// response.end("<h1>Hello, World!</h1>");
// });
app.use('/', website);
app.use('/api', api);
app.listen(port);
console.log('http(s) server revved up on port ' + port);
Any help would rock!
Update: I see, because '/api' matches '/', website gets applied to all routes. Is there any way to avoid this?
probably define the /api router first and the other one - second.
app.use('/api', api);
app.use('/', website);