Why doesnot the index route changes not work? - node.js

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');

Related

All pages return the same content with OVH Cloud Hosting

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.

express.router throws 404 if routes mentioned in separate file

I am having trouble and have already spent quite a time to figure out the cause but to no avail. I have researched and feel like I am doing right but obviously I missing out something.
Here is my app.js:
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var bodyParser = require('body-parser');
var session = require('express-session');
app.use(express.static('./server/static/'));
app.use(express.static('./client/dist/'));
// tell the app to parse HTTP body messages
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser()); // read cookies (needed for auth)
//routes
var authRoutes = require('./server/routes/auth');
app.use('/auth', authRoutes);
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000);
});
And here is the separate auth (routes file):
var express = require('express');
var router = express.Router();
router.post('/signup', (req, res, next) => {
console.log("im in");
});
module.exports = router;
After running this, I get 404 response:
POST http://localhost:3000/signup 404 (Not Found)
If I put the routes in app.js file, I get the desired output. Can someone please help me figure out what is that I am doing wrong?
Try http://localhost:3000/auth/signup
app.use('/auth', authRoutes); exposes the authRoutes on paths starting with /auth.

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;
})();
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.

Express.js - export/access function within route file

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());

App is Running But Not Opening in Browser? It shows Page Not Available

In console it shows message that app/server is running but when I open app in browser it show page not available.
Here's my code for the server initialization (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 server = require('http').Server(app);
var io = require('socket.io')(server);
var app = express();
var viewRoute = require('./routes/view'),
apiRoute = require('./routes/api');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
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('/', viewRoute);
app.use('/api', apiRoute);
server.listen(9190, function(){
var host = server.address().address,
port = server.address().port;
console.log("Server Running # http:%s:%s", host, port);
});
And my file with the routes (api.js):
var express = require('express');
var api = express.Router();
module.exports = (function() {
api.get('/', function(req, res, next) {
console.log("GET Request for Index Page");
});
api.get('/home', function(req, res, next) {
console.log("GET Request for Home Page");
});
return api;
})();
I've already searched google and every other resources but can't find solution.
It seems you are not sending response back to browser,
in api.js change api.get('/' code to like following:
api.get('/', function(req, res, next) {
res.send("Yes Its working now");
});
You're not sending anything back to the client, so nothing shows up in your browser. Use res.send or similar for this.
I'd suggest to change your code for something like this, and see if this works :
var express = require('express'),
app = exports = module.exports = express();
app.get('/', function (req,res) {
console.log("GET Request for Index Page");
res.send("GET / - 200");
});
app.get('/home', function (req,res) {
console.log("GET Request for home Page");
res.send("GET /home - 200");
});
I removed the exported function immediate call by the way.
I also had same issue, My server was running but i was not able to open my app on browser, Uninstalling skype worked for me.

Resources