NodeJS mongo-express error: Cannot GET / - node.js

i'm trying to use Mongo-Express to lookup my mongoDB, I newbee, after i went under the user and pass i got error -> Cannot GET /
var express = require('express')
, routes = require('./routes')
, http = require('http');
var _ = require('underscore');
var async = require('async');
var utils = require('./utils');
var mongodb = require('mongodb');
var cons = require('consolidate');
var swig = require('swig');
var swigFilters = require('./filters');
var app = express();
var config = require('./config');
//Set up swig
app.engine('html', cons.swig);
Object.keys(swigFilters).forEach(function (name) {
swig.setFilter(name, swigFilters[name]);
});
//App configuration
app.configure(function(){
if(config.useBasicAuth){
app.use(express.basicAuth(config.basicAuth.username, config.basicAuth.password));
}
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.set('view options', {layout: false});
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(config.site.baseUrl,express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.cookieParser(config.site.cookieSecret));
app.use(express.session({
secret: config.site.sessionSecret,
key: config.site.cookieKeyName
}));
app.use(express.methodOverride());
app.use(app.router);
});

First of all, try to learn from actual/updated tutorials. Actual express version is 4, and it removes:
app.use(app.router);
(therefore my deduction of outdated tutorial)
Second thing, i dont see in your code any routes. If you want to get responses from server, you need to write routes. For example:
app.get('/test', function(req, res) {
res.send('Hello from route');
});

Related

Nodejs CANNOT GET

I've been trying to do a route in Express. For example one /about route, but it doesn't work.
var express = require('express');
var app = express();
var router = express.Router();
var moment = require('moment');
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.get('/', function (req, res) {
//some action
});
app.get('/time', function (req, res) {
//...
});
app.get('/about', function (req, res) {
res.send('about');
});
Currently after calling url/about I'm getting Cannot GET /about as a return and after some research I've got no idea how to resolve this issue. They even describe it that way in the official express docs.
Thank you in advance.
You have something like this in your code? :
app.listen(SERVER_PORT, function () {
console.log("Server successfully started on port:" + SERVER_PORT); });
We should have something like this:
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
const app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/about', routes.about);
and also in the views folder: about.jade

Node.js , Express ejs views error

EJS Error: Failed to lookup view "admin_landing2" in views directory "/Users/aryanarora/Desktop/asn3/views".
while trying make a call to localhost/8080/yolo
I am getting the same error even if I switch to hbs. (i have installed both the packages)
var express = require("express");
var app = express();
var port = process.env.PORT || 8080;
var path = require('path');
var bodyParser = require('body-parser')
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var fs = require('fs');
// const hbs = require('hbs');
// hbs.registerPartials(__dirname + './views');
// app.set('view engine','hbs');
// Require static assets from public folder
app.use(express.static(path.join(__dirname, 'public')));
// Set 'views' directory for any views
// being rendered res.render()
app.set('views', path.join(__dirname, 'views'));
// Set view engine as EJS
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');
var users = [];
//app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/', function(req,res,next){
console.log(req.method, 'request:', req.url);
next();
});
app.locals.yolo = require('./Data/courses.json');
//Request i am trying to get//
app.get('/yolo',function(req,res){
//res.sendFile(path.join(__dirname + '/admin_landing2.hbs'));
res.render('admin_landing2', {var1 : "pehla" , var2 : "dusra"});
});
app.get('/login', function(req,res){
res.sendFile(path.join(__dirname + '/admin_login.html'));
var filepath = './admin_login.html';
console.log(filepath);
});
The problem is that you're setting the views directory to the wrong location.
Do
app.set('views', __dirname)
instead of
app.set('views', path.join(__dirname, 'views'))

How could router be "undefined" here in my Node app?

var express = require('express')
var router = express.Router();
I am debugging my Node app and express is defined, but after stepping over the var router line, router is still undefined, how could this happen?
Well here is all the code if you must:
var express = require('express')
// , fancy_scripts = require('./fancy_scripts')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// New Code
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/sparks');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.engine('html', require('ejs').renderFile);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(__dirname + '/fancy_scripts'));
app.use('/fancy_scripts', express.static(__dirname + '/fancy_scripts'));
app.use(function(req,res,next){
req.db = db;
next();
});
app.get('/', routes.index);
//var router = express.Router();
//
///* GET home page. */
//router.get('/', routes.index);
If were to guess the line app.use(app.router);
might be the culprit...?

Using piler with express 3 and nodejs

I want to run Express 3.3.x with its default implementation.
Express uses its routes module, so what I have to do, if JS and CSS is accessible by any view in any route?
/**
* Module dependencies.
*/
var express = require('express');
var http = require('http');
var path = require('path');
var piler = require('piler');
var mongoose = require('mongoose');
var config = require('./config');
var app = exports.app = express();
var js = piler.createJSManager();
var css = piler.createCSSManager();
var srv = require('http').createServer(app);
// all environments
js.bind(app,srv);
css.bind(app,srv);
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(require('less-middleware')({ src: __dirname + '/public' }));
app.use(express.static(path.join(__dirname, 'public')));
js.addUrl("http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js");
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
/**
* Routes
*/
var routes = require('./routes');
app.get('/', routes.index);
srv.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
In the example of piler:
app.get("/", function(req, res){
res.render("index.jade", {
layout: false,
js: js.renderTags(),
css: css.renderTags()
});
});
This works. But I have
app.get('/', routes.index);
So what I have to do, that js.renderTags() works in every view?
If you are trying to pass variables to render, you can use res.locals
app.use(function(req,res,next){
res.locals.layout= false;
res.locals.js= js.renderTags();
res.locals.css= css.renderTags();
next();
});
Use this before your router but don't overwrite your locals (res.locals={...})

nodejs - req.body is undefined

I want to post some data to server. The problem is that, it seems the server cannot receive the data.
So my post data is like this:
name=hello&email=there&message=sometext
and my server code is like this:
var url = require('url'),
express = require('express'),
http=require('http'),
path = require('path'),
nodemailer = require('nodemailer');
var app = express();
var server = http.createServer(app);
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.render('home');
});
app.use(express.bodyParser());
app.post('/', function(req, response){
console.log(req.body);
// console.log(request.body.name);
});
server.listen(4000);
console.log('server running ' + 'now ' + Date.now());
when the console.log(reg.body) run, the terminal output is "undefined"
All query strings output are parsed by default by app.use(express.bodyParser());.. simple solution to your problem is try logging req.query , something like
console.log(req.query);
move app.use(express.bodyParser())); ahead of app.use(express.static(path.join(__dirname, 'public')));

Resources