Satya Narayana Satya Narayana - 12 days ago 6
Node.js Question

Getting invalid URL message in expressjs code

I am new to express.js coding. In my code below i want to access two URLs like http://localhost:3000 and http://localhost:3000/fetch to serve different requests using get method. While accessing the first URL i am able to get the response but while accessing second URL i am getting 404 error. I am unable to figure out the issue, can you please help me out in this.

Below are my files:

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 fetch = require('./routes/fetch');

var app = express();


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use('/fetch',fetch);
app.use('/', index);

// 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: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('SmartBin: Invalid URL');
err.status = 404;
next(err);
});

modules.export=app;


index.js

var express = require('express');

/* GET home page */
module.exports = (function() {
var path = require('path');
var bodyParser = require('body-parser');
var db = require('./dbclient');
db.dbconnection(null,null,null,null,'smartbin',null);
var router = express.Router();
router.get('/', function(req, res, next) {
//res.render('index', { title: 'Express' });
db.get('devicereg',{}).then(function(v){
//for (i=0; i<v.length-1; i++)
//res.json(v[i]);
res.json(v);//.end();
}).catch(function(v){
console.log('[SmartBin:Error ' + v);
});
});
return router;
})();


fetch.js

var express = require('express');

/* GET home page. */
module.exports = (function(){
var path = require('path');
var bodyParser = require('body-parser');
var router = express.Router();
var db = require('./dbclient');
db.dbconnection(null,null,null,null,'smartbin',null);
router.get('/fetch', function(req, res, next) {
db.get('devicereg',{}).then(function(v){
res.json(v);
}).catch(function(v)
{console.log('[SmartBin:Error ' + v);}
);
});
return router;
})();

Tom Tom
Answer

I think you could try one of these options:

1. Minor changes:

In your app.js use the app.use('/', index) and app.use('/', 'fetch'). Your route is set inside the index.js and fetch.js files, so it should work, even not having in your app.js the code app.use('/fetch', 'fetch').

In your existing code you probably can access http://localhost:3000/fetch/fetch (because you are declaring /fetch in app.js and then declaring again /fetch in fetch.js file).

2. Pass app by parameter to the route file:

In your app.js, try to require your route files passing your instance of app, instead of app.use('/', index) and app.use('/fetch', fetch).

E.g.:

app.js

var express = require('express');
var app = express();

// Comment these lines
//app.use('/fetch',fetch);
//app.use('/', index);

// Add this lines passing the instance of 'app' you've created
var indexRoute = require('./routes/index')(app)
var indexFetch = require('./routes/fetch')(app)

In your route files, try to adapt as the following:

index.js

module.exports = function(app) {
    app.get('/', function(req, res) {
        res.send("This is index");
    });
}

fetch

module.exports = function(app) {
    app.get('/fetch', function(req, res) {
        res.send("This is fetch");
    });
}

Hope it helps.

Comments