Nodejs shows Error "Cannot GET /test" - node.js

I am trying to retrieve output on other url / directory in nodejs but it's Display Error ("Cannot GET /test").
Please Suggest me what i have to do to get my output on ("http://localhost:8080/test").
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
var session = require('express-session');
var cookieParser = require('cookie-parser');
app.set('view engine', 'pug');
app.set('views','./views');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.array());
app.use(cookieParser());
app.use(session({secret: "Your secret key"}));
var Users = [];
app.get('/', function(req, res){
res.render('signup');
});
app.post('/signup', function(req, res){
if(!req.body.id || !req.body.password){
res.status("400");
res.send("Invalid details!");
} else {
Users.filter(function(user){
if(user.id === req.body.id){
res.render('signup', {
message: "User Already Exists! Login or choose another user id"});
}
});
var newUser = {id: req.body.id, password: req.body.password};
Users.push(newUser);
req.session.user = newUser;
res.redirect('/test');
}
});
app.listen(8080);
OutPut : Cannot GET /test

You did not specify a route for /test. You should have
app.get('/test', function(req, res, next){
res.render('test'); // This should have a view
});

Here i writing sample. create views folder in root folder and add one test.pub file to views then just run
Note:dont forget to install pug and express
var express = require('express')
var app = express()
app.set('view engine', 'pug');
app.set('views','./views');
// here am directly sending response without using view engine
app.get('/', function (req, res) {
res.send('hello world')
})
// here am sending response with using view engine
app.get('/test', function(req, res){
res.render('test');
});
app.listen(8000,function(){
console.log(" Server is running on port 8000");
});

Related

How to debug 404 error in Nodejs web application?

I am working on a Nodejs Web application project which is based on Express Framework. I am working on creating a Sign up page. After giving the username and password the url should be redirected to profile page. In the views folder I created a file "profile.hbs". But the profile is not being recognized and I getting 404 not found. Please share your ideas on how to debug this issue.Thanks in advance.
app.js
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 mongoose=require('mongoose');
var session=require('express-session');
var passport=require('passport');
var flash=require('connect-flash');
const mocha=require('mocha');
var validator=require('express-validator');
var indexRouter = require('./routes/index');
//var usersRouter = require('./routes/users');
var app = express();
mongoose.connect('mongodb://localhost:27017/shopping');
require('./config/passport');
// view engine setup
app.engine('.hbs',expressHbs({defaultLayout:'layout',extname:'.hbs'}));
app.set('view engine', '.hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(validator());
app.use(cookieParser());
app.use(session({secret:'mysupersecret',resave:false,saveUninitialized:false}));
app.use(passport.initialize());
app.use(flash());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
//app.use('/users', usersRouter);
// 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) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Routing file
var express = require('express');
var router = express.Router();
var csrf=require('csurf');
var passport=require('passport');
const canine= require('../models/dogfood');
var csrfProtection=csrf();
router.use(csrfProtection);
/* GET home page. */
router.get('/', function(req, res, next) {
canine.find(function(err,docs){
var productChunks=[];
var chunkSize=3;
for(var i=0;i<docs.length;i += chunkSize){
productChunks.push(docs.slice(i,i+chunkSize));
}
res.render('shop/index', { title: 'Express',diets:productChunks});
});
});
router.get('/user/signup',function(req,res,next){
res.render('user/signup',{csrfToken:req.csrfToken()})
});
router.post('user/signup',passport.authenticate('local.signup',{
successRedirect:'user/profile',
failureRedirect:'user/signup',
failureFlash:true
}));
router.get('user/profile',function(req,res,next) {
res.render('user/profile');
});
module.exports = router;
Apart from adding a view file you should also add a new route which renders that view
app.get('/', function (req, res) {
res.render('profile.hbs', {
title: 'Profile',
// and any extra data you need, probably coming from your auth middleware
});
});

NodeJs routes not working from inner page

I am trying to develop an application in NodeJs using express framework. My routing is working when I navigating from home to inner pages. But If I want to navigate from some inner page to homepage then it is not working.
Below is my app.js code.
const express = require('express');
const path = require('path');
const engines = require('consolidate');
const bodyParser = require('body-parser');
//declare all routers
var home = require(path.join(__dirname, "/routes/index"));
var myaccount = require(path.join(__dirname, "/routes/myaccount"));
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.engine('html', engines.handlebars);
var defaultViewPath = path.join(__dirname, "/views");
app.set('views', defaultViewPath);
app.set('view engine', 'html');
app.use('/', home);
app.use('/myaccount', myaccount);
Here if I have navigated from home to myaccount - Its working
But if I am navigating from myaacount to home - It reloads the same page.
Can anyone help me to resolve this issue.
To define routing using methods of the Express app object, use app.get() to handle GET requests
var express = require('express')
var app = express()
// When GET request is made to the homepage
app.get('/', function (req, res) {
res.render('home');
});
// When GET request is made to the myaccount
app.get('/myaccount', function (req, res) {
res.render('myaccount');
});
app.get('/myaccount/innerpage', function (req, res) {
res.send('Hello Inner Page');
});
//Page Not Found
app.use(function(req, res){
//render the html page
//res.render('404');
res.sendStatus(404);
});
Hope this could help you
use app.get and app.post Route Methods
app.get('/',function(req,res){
res.render('home');
});
app.get('/myaccount',function(req,res){
res.render('myaccount');
});
Or Create Router File For Home & myAccount
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('Home Page')
})
module.exports = router
in Your app.js or index.js file , require route.js
var home = require('./route');
app.use('/', home)

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.

How to get post params in app.post

I am developing nodejs project. Where I am using ejs with the help of express-helpers module to generate view template html.
in server.js file I have written below code
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
var app = express();
var helpers = require('express-helpers')
helpers(app);
var server = http.Server(app);
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
var addr = server.address();
console.log("Chat server listening at", addr.address + ":" + addr.port);
});
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/public/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
//app.use(express.static(__dirname + '/client'));
app.use(express.static(path.join(__dirname, '/client')));
// respond with "index.html" when a GET request is made to the homepage
app.get('/', function(req, res) {
res.render('index.html');
});
app.get('/demo', function (req, res) {
res.render('demo.ejs');
});
app.post('/demo', function (req, res) {
console.log(res.body)
});
I want to know that in app.post how should id get post params
app.post('/demo', function (req, res) {
console.log(res.body)
});
I have tried console.log(req.body) but giving as undefined
Also tried console.log(res.body) but giving as undefined
Let me know how should I implement it?
you should use a middleware such as body-parser
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post('/demo', function (req, res) {
console.log(req.body)
});
Use the body-parser middleware. First, you need to install it using npm install body-parser. And then use it in your application like this
var bodyParser = require('body-parser');
.....
// For Content-Type application/json
app.use(bodyParser.json());
// For x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
....
app.post('/demo', function (req, res) {
console.log(req.body);
});

Express.js and Node.js : Unable to set value in the request object

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)

Resources