router.get('/') on expressjs not working - javascript

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");
});

Related

db.getConnection is not a function

I am trying to make a post request to my first app, but every time I go to make the post, it gives me this error: TypeError: db.getConnection is not a function
I have tried all of stack overflows suggestions, but I still can't seem to get it to work after messing around with the code for the last 2 days. I am a beginner so please forgive me, but here is what my code looks like...
my db.js looks like this....
var mysql = require('mysql');
var mainDb = mysql.createPool({
host : process.env.mysql_host,
user : process.env.mysql_user,
password : process.env.mysql_pwd,
database : process.env.mysql_db
});
exports.getConnection = function(callback) {
mainDb.getConnection(function(err, connection) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
callback(err, connection);
});
};
and my register.js code looks like this...
var express = require('express');
var router = express.Router();
var db = require(__dirname, 'models/db');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
router.get('/register', function(req, res, next) {
res.render('register', { title: 'Register for a free account' });
});
router.post('/register', function(req, res) {
var input = JSON.parse(JSON.stringify(req.body));
var today = new Date();
var users = {
"username": req.body.username,
"email":req.body.email,
"password":req.body.password,
"created":today,
"modified":today
};
db.getConnection(function(err, connection) {
connection.query('INSERT INTO users SET ? ', users, function(err, result) {
connection.release();
if (err) { return console.error(err); }
});
});
res.redirect('/index');
});
module.exports = router;
I don't know if my app.js is relevant for this question, but it looks like this...
const express = require('express');
http = require('http');
path = require('path');
session = require('express-session');
app = express();
mysql = require('mysql');
bodyParser = require('body-parser');
db = require(__dirname, 'models/db')
var index = require('./routes/index');
var register = require('./routes/register');
app.use('/', index);
app.use('/', register);
var engine = require('ejs-mate');
app.engine('ejs', engine);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
var server = http.createServer(app);
var port = 8995;
server.listen(port);
module.exports = app;
When I start app.js I get no errors, only when I make my post request from my form, the error shows up in my browser. Please help!
At db.js you are exporting only a function. But at register.js, you are trying to use db as if it was an object.
To solve your problem, at db.js, just export an object, instead of a function:
function getConnection(callback) {
mainDb.getConnection(function(err, connection) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
callback(err, connection);
}
module.exports = { getConnection };
You don't need use getConnection method only exports the pool, according the documentation.
https://github.com/mysqljs/mysql

Express: Serving static files for defined routes

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.

Creating an HTTPs server with Node.js and Express

var https = require('https'),
fs = require('fs'),
express = require('express'),
app = express();
// cookieParser = require('cookie-parser'),
// path = require('path'),
// bodyParser = require('body-parser'),
// https = require('http');
var key = fs.readFileSync('encryption/star_massifsolutions_com.key');
var cert = fs.readFileSync('encryption/massif_wildcard.crt');
var ca = fs.readFileSync('encryption/DigiCertCA.crt');
var httpsOptions = {
key: key,
cert: cert,
ca: ca
};
https.createServer(httpsOptions, app).listen(8000, function () {
console.log("server running at https://IP_ADDRESS:8000/")
});
app.get('/', function (req, res) {
res.header('Content-type', 'text/html');
return res.end('Hello World!');
});
// app.set('view', __dirname + '/views');
// app.use(bodyParser.urlencoded({
// extended: true
// }));
// app.use(bodyParser.json({
// limit: '500mb'
// }));
// app.use('/', express.static(path.join(__dirname, '/dist/basic-structure')));
// app.get('/**', function (req, res, next) {
// console.log(req, res, next);
// res.sendFile('index.html', {
// root: __dirname + '/dist/basic-structure'
// });
// });
console.log("listening to port 8000");
Here i have written hello world just to test my code.so in this case code runs but its not secure. I want my connection to be secure.In this case it shows deprecated http and shows certificate error.but and run unsecurly.
Again if I replace the hello world part with the commented part as shown in my code it doesn't even run with the deprecated http.if i replace the https with http it runs. I want help in running my edited code. If i am missing some points please let me know.
In short this code is running insecurly , i want to make it secure
Not sure if I understand well, but if by "the code is not running" you mean your app, then it seems your 2nd code set simply try to run a server but not your app
To my understanding, you are defining your app as express but you are not using it, so it will not be delivered
So my guess is that you will need to use the https server command with the app and its options to link everything together (https and app) as suggested by #lx1412
I would try this :
var express = require('express'),
cookieParser = require('cookie-parser'),
path = require('path'),
bodyParser = require('body-parser'),
// https = require('http'),
https = require('https'),
app = express(),
fs = require('fs');
var key = fs.readFileSync('encryption/star_massifsolutions_com.key');
var cert = fs.readFileSync( 'encryption/massif_wildcard.crt' );
var ca = fs.readFileSync( 'encryption/DigiCertCA.crt' );
var httpsOptions = {
key: key,
cert: cert,
ca: ca
};
app.set('view',__dirname+'/views');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json({limit: '500mb'}));
app.use('/', express.static(path.join(__dirname,'/dist/basic-structure')));
app.get('/**', function(req, res, next) {
console.log(req, res, next);
res.sendFile('index.html', { root: __dirname +
'/dist/basic-structure' });
});
// https.createServer(httpsOptions, (req, res) => {
// console.log("code works");
// res.writeHead(200);
// res.end('hello world\n');
// }).listen(8000);
https.createServer(httpsOptions, app).listen(8000, function () {
console.log("code works");
res.writeHead(200);
res.end('hello world\n');
});
EDIT :
Can you simply try this and see how it behaves ?
Also, can you provide your deprecated http and certificate error ?
app.get('/', function (req, res) {
res.send('Hello World!');
});
https.createServer(httpsOptions, app).listen(8000, function () {
console.log("server running at https://IP_ADDRESS:8000/")
});
It's simple.
var express = require('express'),
cookieParser = require('cookie-parser'),
path = require('path'),
bodyParser = require('body-parser'),
http = require('http'),
app = express();
app.set('view',__dirname+'/views');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json({limit: '500mb'}));
app.use('/', express.static(path.join(__dirname,'/dist/basic-structure')));
app.get('/**', function(req, res, next) {
console.log(req, res, next);
res.sendFile('index.html', { root: __dirname +
'/dist/basic-structure' });
});
//Start Server
//app.listen(3004, function(){
// console.log('>>>3004')
//});
//complete your code here
https.createServer(httpsOptions,app).listen(8000);

Express Js: Router.use() Requires Middleware function

I am developing an application in Express Js. When I try to run the application I get this error:
My app.js file is like this:
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 app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
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
});
});
}
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
module.exports = router;
My index.js is like this:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function (req, res, next) {
res.render('index', {title: 'Polls'});
});
router.get("/list", function (req, res, next) {
Poll.find({}, 'question', function (error, polls) {
res.json(polls);
});
});
router.get("/poll", function (req, res, next) {
var pollId = req.params.id;
// Find the poll by its ID, use lean as we won't be changing it
Poll.findById(pollId, '', {lean: true}, function (err, poll) {
if (poll) {
var userVoted = false,
userChoice,
totalVotes = 0;
// Loop through poll choices to determine if user has voted
// on this poll, and if so, what they selected
for (c in poll.choices) {
var choice = poll.choices[c];
for (v in choice.votes) {
var vote = choice.votes[v];
totalVotes++;
if (vote.ip === (req.header('x-forwarded-for') || req.ip)) {
userVoted = true;
userChoice = {_id: choice._id, text: choice.text};
}
}
}
// Attach info about user's past voting on this poll
poll.userVoted = userVoted;
poll.userChoice = userChoice;
poll.totalVotes = totalVotes;
res.json(poll);
} else {
res.json({error: true});
}
});
});
router.get("/create", function (req, res, next) {
var reqBody = req.body,
// Filter out choices with empty text
choices = reqBody.choices.filter(function (v) {
return v.text != '';
}),
// Build up poll object to save
pollObj = {question: reqBody.question, choices: choices};
// Create poll model from built up poll object
var poll = new Poll(pollObj);
// Save poll to DB
poll.save(function (err, doc) {
if (err || !doc) {
throw 'Error';
} else {
res.json(doc);
}
});
});
module.exports = router;
And user.js is this:
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
I tried to find my solution on SO, but couldn't. Feel free to tell me if i need to provide any other file. Any help?
You should define routes in your index.js like you do in user.js.
app.use('/', routes) in your code expects routes to be an instance of a Router, but you're exporting an object with functions instead of that.
So your index.js file should have the following structure:
var express = require('express');
var router = express.Router();
router.get("/", function (req, res) {
res.render('index');
});
router.get("/list", function(req, res) {/*list implementation*/});
....
module.exports = router;

express (4.0) custom middleware runs on both instances of router even though it's only declared for one

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

Categories