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;
})();
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.
Related
I created a new app using the express generator without any view engine. I go to http://127.0.0.1:3000 which shows the standard express welcome view. Then I add some query params to url like http://127.0.0.1:3000/?test1=testing&test2=testing234 and try to access these in the indexRouter's index.js but cannot access the query params. I tried
req.query.test1
and all other variants nothing works. Then I commented the line
app.use('/', indexRouter);
but I still can access the welcome screen. Commenting the below line throws error which i think is how it works as it is serving a static file.
app.use(express.static(path.join(__dirname, 'public')));
Is there any way I can access the query params in the home url in index router? What am I missing here?
app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// app.use('/', indexRouter);
app.use('/users', usersRouter);
module.exports = app;
indexRouter
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function (req, res, next) {
console.log(req, 'request');
console.log(res, 'response');
res.render('index', { title: 'Express' });
});
module.exports = router;
You can access the req params by commenting out
// app.use(express.static(path.join(__dirname, 'public')));
And, change the response method
Instead of rendering the static file
// res.render('index', { title: 'Express' });
res.send('something');
I've recently completed a Node.js website locally, which works fine, though I have noticed some issues when uploading the website online to OVH Cloud Web Hosting. All pages, even those that should not exist, return the contents of the homepage.
I'm running Express with Node.js, and the file structure was created with express-generator. My app.js file contains the following:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var expressHbs = require('express-handlebars');
var Handlebars = require('handlebars');
var HandlebarsIntl = require('handlebars-intl');
var mongoose = require('mongoose');
var indexRouter = require('./routes/index');
var blogRouter = require('./routes/blog');
var blogItemRouter = require('./routes/blog-item');
var portfolioRouter = require('./routes/portfolio');
var contactRouter = require('./routes/contact');
var iBlogPostsRouter = require('./routes/i/blog-posts');
var iContactRouter = require('./routes/i/contact');
var iPortfolioItemsRouter = require('./routes/i/portfolio-items');
var portfolioItemRouter = require('./routes/portfolio-item');
HandlebarsIntl.registerWith(Handlebars);
var app = express();
// view engine setup
app.engine('.hbs', expressHbs({defaultLayout: 'layout', extname: '.hbs'}));
app.set('view engine', '.hbs');
app.disable('etag');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/blog', blogRouter);
app.use('/blog/:title', blogItemRouter);
app.use('/portfolio', portfolioRouter);
app.use('/contact', contactRouter);
app.use('/i/blog-posts', iBlogPostsRouter);
app.use('/i/contact', iContactRouter);
app.use('/i/portfolio-items', iPortfolioItemsRouter);
app.use('/portfolio/:title', portfolioItemRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {title: err.status + ' ' + err.message});
});
module.exports = app;
All of the routers have the same code, except render a different template. Here is an example of the indexRouter:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'About', about: true });
});
module.exports = router;
The issue is that every page, even my .js and .css files, returns the HTML from whatever is in the app.use('/' ...) router. The console returns the following error:
Resource interpreted as Stylesheet but transferred with MIME type text/html: "https://xxx.co.uk/core/styles/m.css".
I experimented with this by changing the homepage to be my contact page, which has resulted in every URL returning the contact page. My CSS and JavaScript are in a public folder. The only thing that I can think of is that the '/' route is somehow being used for every single request, but it doesn't make any sense to me why this could be happening.
Instead of using app.use('/<route>', <router>) in your project, try replacing it with the corresponding express statements, e.g,
router.<route_method>('/<route>', function(req, res, next){
// code
});
See if it works fine or not.
The reason your site is defaulting to the '/' route is because you haven't properly set up your routes. Each router module needs to know what is getting exported. Your indexRouter file, for example, needs to look like this:
var express = require('express');
var router = express.Router;
router.get('/', function(req, res){
res.render('index', { title: 'About', about: true });
});
module.exports = router; <<----
In addition, if the app.js you're showing as of 09/04/2018 06:36 is the complete app.js, you're missing a lot. You have a minimized CSS as your first stylesheet, which actually contains the rendered index.html.
This is the picture of my server
https://drive.google.com/file/d/1GA57RyYsc5ik1pSlLhAGtgGjbp_vLFoH/view?usp=sharing
When I go to http://localhost:3000/
I get the error message: Cannot Get/
myserver.js
// TODO: mount the tigers route with a a new router just for tigers
// exactly like lions below
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var _ = require('lodash');
var morgan = require('morgan');
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
app.use(morgan('dev'))
app.use(express.static('client'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// this is called mounting. when ever a req comes in for
// '/lion' we want to use this router
app.use('/lions', lionRouter);
app.use(function(err, req, res, next) {
if (err) {
res.status(500).send(error);
}
});
app.listen(3000);
console.log('on port 3000');
Whenever you are trying to visit any url on the browser , then browser makes a GET request to that url, in your case you are not sending any response on the url: "http://localhost:3000/. You can try something like this.
app.route('/*')
.get(function(req, res) {
res.sendFile(path.resolve("./client") + '/index.html'));
});
Check the naming you used, it shows myserver.js instead of server.js as in the picture you uploaded.
Check your routing on line 10 of you code
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
. try this edited codes
server.js
// TODO: mount the tigers route with a a new router just for tigers
// exactly like lions below
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var _ = require('lodash');
var morgan = require('morgan');
var lionRouter = require('./server/lions');
var tigerRouter = require('./server/tigers');
app.use(morgan('dev'))
app.use(express.static('client'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// this is called mounting. when ever a req comes in for
// '/lion' we want to use this router
app.use('/lions', lionRouter);
app.use(function(err, req, res, next) {
if (err) {
res.status(500).send(error);
}
});
app.listen(3000);
console.log('on port 3000');
Express static directory is given client but it is present on parent directory.
So i have resolve this issue with path module and now this will work for you.
// TODO: mount the tigers route with a a new router just for tigers
// exactly like lions below
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var _ = require('lodash');
var morgan = require('morgan');
var path = require('path')
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
app.use(morgan('dev'))
app.use(express.static(path.join(__dirname, '../client')));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// this is called mounting. when ever a req comes in for
// '/lion' we want to use this router
app.use('/lions', lionRouter);
app.use(function(err, req, res, next) {
if (err) {
res.status(500).send(error);
}
});
app.listen(3000);
console.log('on port 3000');
Your code works fine after commenting the following three lines of your code:
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
app.use('/lions', lionRouter);
Check if any error is present in LionsJS.
I am trying to export function within route file. Here is my code
app.js file
var express = require('express');
var bodyParser = require('body-parser');
var users = require('./routes/users');
var others=require('./routes/others')
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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('/others', others);
app.use('/users', users);
module.exports = app;
others.js file
var express = require('express');
var router = express.Router();
router.post("/test", function (req, res, next) {
res.send("success");
});
//Here i want to export function to users js file
var funDef=function(){
console.log("export a function")
}
moudle.exports=router;
How can I export or call funDef in users.js file. I tried the following way but it is not working
users.js file
var express = require('express');
var router = express.Router();
var readFun= require("./others.js");
router.post("/testUsers", function (req, res, next) {
res.send("suceess");
});
//getting undefined
readFun.funDef();
module.exports=router;
Can anyone guide me?
Try for the following:
function router() {}
router.prototype.funDef=function(){
console.log("export a function")
}
moudle.exports.router=router;
Another file:
var router = require('router').router;
var Router = new router();
Router.funDef();
EDIT:
// module.js
'use strict';
var temp = "this is a test";
module.exports.func = function() {
return temp;
}
// app.js
'use strict';
var module = require('./module');
console.log(module.func());
I am following Practical Node.js book. It is based on older version on express.js. The book is trying to build a blog. It has several different routes files. Ex- index.js, admin.js, article.js etc. This route classes are called from app.js. Ex:
app.use('/', routes.index);//// THE ISSUE IS HERE /////
app.get('/login', routes.user.login);
app.post('/login', routes.user.authenticate);
app.get('/logout', routes.user.logout);
app.get('/admin', routes.article.admin);
app.get('/post', routes.article.post);
app.post('/post', routes.article.postArticle);
Whenever someone tries to access '/', I am setting a collections object of artices and users in the request object.
var dbarticles = require('./db/articles.json');
var dbusers = require('./db/users.json');
app.use(function(req, res,next) {
if (!collections.articles || ! collections.users) return next(new Error("No collections."))
req.collections = collections;
return next();
});
app.use('/', routes.index);//// THE ISSUE IS HERE /////
The problem is that in index.js file, the value of req.collections is no available, I get 'undefined'. What am I missing. I have checked in the console.log, that the value is present in req.collections before the '/', route.index is hit.
Here's my app.js
var express = require('express');
var router = express.Router();
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var methodOverride = require('method-override');
var routes = require('./routes');
var dbarticles = require('./db/articles.json');
var dbusers = require('./db/users.json');
var collections = {
articles: dbarticles,
users: dbusers
};
var logger = require('morgan');
var errorHandler = require('errorhandler');
var app = express();
app.locals.appTitle = 'blog-express';
//console.log(collections.articles || collections.users);
app.use(function(req, res,next) {
if (!collections.articles || ! collections.users) return next(new Error("No collections."))
req.collections = collections;
return next();
});
// 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(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(methodOverride());
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
// Pages and routes
app.use('/', routes.index);
app.get('/login', routes.user.login);
app.post('/login', routes.user.authenticate);
app.get('/logout', routes.user.logout);
app.get('/admin', routes.article.admin);
app.get('/post', routes.article.post);
app.post('/post', routes.article.postArticle);
app.get('/articles/:slug', routes.article.show);
// REST API routes
app.get('/api/articles', routes.article.list);
app.post('/api/articles', routes.article.add);
app.put('/api/articles/:id', routes.article.edit);
app.delete('/api/articles/:id', routes.article.del);
app.all('*', function(req, res) {
res.sendStatus(404);
})
// catch 404 and forward to error handler
// error handlers
// development error handler
// development only
if ('development' == app.get('env')) {
app.use(errorHandler());
}
// production error handler
// no stacktraces leaked to user
//module.exports = router;
module.exports = app;
Here is my index.js
exports.article = require('./article');
exports.user = require('./user');
/*
* GET home page.
*/
exports.index = function(req, res, next){
console.log(".." + res.collections);
req.collections.articles.find({published: true}, {sort: {_id:-1}}).toArray(function(error, articles){
if (error) return next(error);
res.render('index', { articles: articles});
})
};
If some one needs to take a look at the code base of book, please check this github url - https://github.com/azat-co/practicalnode/tree/master/ch5/blog-express
Try changing app.use('/', routes.index) to app.get('/',routes.index)
If that doesn't work, try setting the middleware inline...
var setCollections = function (req, res,next) {
if (!collections.articles || ! collections.users) return next(new Error("No collections."))
req.collections = collections;
return next();
}
app.get('/', setCollections, routes.index)