Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
});
like image 617
Ashutosh Avatar asked Jan 01 '26 15:01

Ashutosh


2 Answers

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.

like image 151
skirtle Avatar answered Jan 03 '26 09:01

skirtle


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.

like image 44
Syed Ayesha Bebe Avatar answered Jan 03 '26 11:01

Syed Ayesha Bebe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!