I created an express project using the express generator like following
express project_name
and
npm install
This is my 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 routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// 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({ 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);
});
// error handlers
// development error handler
// will print stacktrace
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
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
These are my routes
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'iDanG Management' });
});
module.exports = router;
I have following index.jade
extends layout
block content
div.container
div.row
form(id='myform' action='' method='post')
p Name:
input(type='text' name='name')
p E-Mail:
input(type='text' name='email')
input(type='submit' value='add')
table(class='table table-hover' id='user_table')
thead
tr
th Name
th Email
tbody
script.
$(document).ready(
function() {
$('#user_table').dataTable({
"pagingType": "simple_numbers",
"ordering": false
});
$('#myform').ajaxForm({ beforeSubmit:
function (formData, jqForm, options) {
$('#table').DataTable().row.add([formData[0].value, formData[1].value]).draw();
return false;
}
});
});
And following layout.jade
doctype html
html
head
title= title
script(src="/javascripts/jquery-1.11.2.min.js")
script(src="/javascripts/jquery.form.js")
script(src="/javascripts/jquery.dataTables.min.js")
link(rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css")
link(rel="stylesheet" href="/javascripts/jquery.dataTables.min.css")
body
block content
when I try to submit that form I receive following error:
Error: Not Found
at app.use.res.render.message (/home/ubuntu/iDanG_Management/app.js:30:13)
at Layer.handle [as handle_request] (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:302:13)
at /home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:321:12)
at next (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:261:10)
at /home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:603:15
at next (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:246:14)
at Function.proto.handle (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:166:3)
at router (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:35:12)
For the forms I used this
Do you have any suggestions how I can solve this problem? Help is highly appreciated!
It seems like you are doing a post request and your routes does not have post handler.
May be add route for post:
router.post('/', function(req, res, next) {
//do something and return data here?
});
Related
The basic problem is as follows:
Passing an object from my c# program, which is serialize and send through a socket. Achieved this in node.js/express application with socket.io.
Need to pass this to the client and using pug as the template engine.
Everything tried so far just doesn't seem to be working. Can't access the elements in the object. Pretty new to node and express so please bear with me.
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 routes = require('./app_server/routes/index');
var users = require('./app_server/routes/users');
var app = express();
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
// view engine setup
app.set('views', path.join(__dirname, 'app_server', '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({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
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
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
layout.jade :
doctype html
html
head
meta(name='viewport', content='width=device-width, initial-scale=1.0')
title= title
link(rel='stylesheet', href='/bootstrap/css/amelia.bootstrap.css')
link(rel='stylesheet', href='/stylesheets/style.css')
script(src="https://cdn.socket.io/socket.io-1.4.5.js")
script.
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
body
block content
script(src='/javascripts/jquery-1.11.1.min.js')
script(src='/bootstrap/js/bootstrap.min.js')
index.jade :
extends layout
block content
h1= title
p Welcome to #{title}
//THIS IS WHERE I DON'T KNOW HOW TO ACCESS THE OBJECT AND ITS PROPERTIES
Can see the object in the console so the data is appearing.
Tried many different variations, but nothing seems to be working. Any input or guidance would be welcome.
Thanks in advance.
I am new to Node.js (been doing ASP.Net for ages) and I cannot for the life of me figure out why I am getting this 404.
So in my work on this I have simplified the code down to just the bare minimum.
app.js for the service handler.
app.post('/getdocument', function (req, res) {
console.log('made it');
res.send('made it');
});
The code from the jade file
li: a(onclick="downloadfile('#{pdfUrl}');") Download PDF
And the onclick function
function downloadfile(url){
alert(url);
$.post('/getdocument', {data: url}, function (data) {
alert(data);
});
}
So I get the first alert that it made it into the function, then I get this in the log for the Node Server
POST /getdocument 404 81.910 ms - 1547
I am really at a loss as to why.
-- As Requested here is the entire 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 viewer = require('./routes/viewer');
var app = express();
// 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(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('/public', express.static(path.join(__dirname, 'public')));
app.use('/pdf', express.static(path.join(__dirname, 'public/pdf')));
app.use('/ViewerJS',express.static(path.join(__dirname, 'ViewerJS')));
app.use('/viewer', viewer);
app.post('/getdocument', function (req, res) {
console.log('made it');
res.send('made it');
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
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
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
So it all turned out to be an issue with Node server running. I had to restart to apply Windows updates and now it works.
Take care all!
I have an express v4 server with a route called admin. When the user post a password to the admin route, I want to respond by setting a cookie on the user's browser and sending a small json. For some reason, the server keeps returning error 500 when trying to respond. I'm assuming that this is something to do with the cookie as I can do "res.send()" without any problem. I'm new to express/nodejs so any help is appreciated.
admin.js
var express = require('express');
var router = express.Router();
var cookieParser = require('cookie-parser');
/* POST HANDLER */
router.post('/', function(req, res) {
var on = {'admin' : "on"};
res.cookie(cookie , 'cookie_on').send(on);
});
module.exports = router;
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 routes = require('./routes/index');
var admin = require('./routes/admin');
var blogposts = require('./routes/blogposts');
var app = express();
// 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(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('/', routes);
app.use('/admin', admin);
app.use('/blogposts', blogposts);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
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
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Dumb mistake: Cookie should have been 'cookie'...
I'm fairly new to express js and I want to know how to use router. I created a file named categories.js inside routes directory with this code.
categories.js code:
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/categories', function(req, res) {
res.send('this is the category');
});
module.exports = router;
inside the app.js i have this code:
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 categories = require('./routes/categories');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
// 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({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/categories', categories);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
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
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
I have tried understand what is wrong but i can't see to figure out. thanks in advance.
This is the error im getting
Not Found
404
I will like to add inside the routes directory i have a index.js file and this one works.
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
I think my application is not reading the categories.js file, because when I put the category.js code inside index.js it works. but it doesn't work if i put it in a separate file in my case category.js.
I think you've got your categories route hooked up wrong, your categories are mapped to /categories/categories in your code. To fix it, try this in your app.js:
app.use('/', categories);
If you don't want to prefix, you can also simply do this:
app.use(categories);
I'm trying to run an node.js and mongodb application...
see: http:// 93.188.162.100:3000/MelhoraCidade/ws/mcapp
but i'm getting the following error
Not Found
404
Error: Not Found
at app.use.res.render.message (/home/ladessa/files/MelhoraCidade/ws/mcapp/app.js:30:15)
at Layer.handle [as handle_request] (/home/ladessa/files/MelhoraCidade/ws/mcapp/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/home/ladessa/files/MelhoraCidade/ws/mcapp/node_modules/express/lib/router/index.js:271:13)
at /home/ladessa/files/MelhoraCidade/ws/mcapp/node_modules/express/lib/router/index.js:238:9
at Function.proto.process_params (/home/ladessa/files/MelhoraCidade/ws/mcapp/node_modules/express/lib/router/index.js:313:12)
at /home/ladessa/files/MelhoraCidade/ws/mcapp/node_modules/express/lib/router/index.js:229:12
at Function.match_layer (/home/ladessa/files/MelhoraCidade/ws/mcapp/node_modules/express/lib/router/index.js:296:3)
at next (/home/ladessa/files/MelhoraCidade/ws/mcapp/node_modules/express/lib/router/index.js:190:10)
at /home/ladessa/files/MelhoraCidade/ws/mcapp/node_modules/express/lib/router/index.js:192:16
at Function.match_layer (/home/ladessa/files/MelhoraCidade/ws/mcapp/node_modules/express/lib/router/index.js:296:3)
I used "express mcapp" to create the app....
EDIT app.js code:
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();
// 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({ 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);
});
// error handlers
// development error handler
// will print stacktrace
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
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;