I know that there were asked similar questions to the issue:
I use formidable with express . And I see that 'fileBegin' event was not fired while 'file' event was fired.
Here are express definitions :
var app = express();
// all environments
process.env.port = 3001;
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(express.static(path.join(__dirname, 'public')));
Is there missing something in definitions? Thanks in advance
Update : upload handler :
function parseFormData(req,res,uploadDir){
var form = new formidable.IncomingForm();
var files = [];
try {
form.uploadDir = uploadDir;
form.parse(req, function() {
});
var logMsg;
form
.on('file',function(name, file) {
console.log('file found');
logMsg = util.format('Filename :%s\nFilesize: %s\nFilepath %s',file.name,file.size,file.path);
console.log(logMsg);
files.push(file);
})
.on('fileBegin',function(name, file) {
console.log('fileBegin file.name: '+file.name);
var targetFolder = path.dirname(file.path);
file.path = path.join(targetFolder,file.name);
console.log('new path: '+file.path);
})
.on('end', function() {
console.log(util.inspect(files));
res.writeHead(200);
res.end('done');
console.log('end');
});
}
catch(error){
res.end('done');
}
}
Related
I am a newbie to use express and as a result am bungling my way through making this web app.
I have my routes in a different file called route.js inside a module.export, and I manage all this inside app.js and I want to be able to serve a HTML page and keep it in the module. I've done so using sendFile but it doesn't serve the CSS and JS as well. What can I do to fix this?
app.js
//setup
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 users = require('./routes/users');
var app = express();
var port = process.env.PORT || 3000;
var mongoose = require('mongoose');
var flash = require('connect-flash');
var passport = require('passport');
var session = require('express-session');
var path = require('path');
//db
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
require('./config/passport')(passport);
// view engine setup
//app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'jade');
app.set('view engine', 'ejs');
//routes
//app.use('/', index);
//app.use('/users', users);
// 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')));
//passport
app.use(session({secret: 'secret'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
//routes
require('./app/routes.js')(app, passport);
// 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 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;
//launch
app.listen(port);
console.log('Website starting on port ' + port);
routes.js
module.exports = function(app,passport) {
...
//--timesheet section---
app.get('/timesheet', function(req, res) {
var path = require('path');
res.sendFile(path.resolve('public/timesheet.html'));
});
...
}
You want to use a view engine and a static directory. You have some of the code already.
Your view engine using .ejs:
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
And you can define your static and specify a path prefix:
app.use('/assets', express.static(path.join(__dirname, 'public')));
In your views directory, put your htmls with .ejs extension, such as timesheet.ejs. You can then create an assets directory for your css/js/image files and reference them in your timesheet.ejs using /assets/style.css.
Finally, in your route, you'll want to render the template:
res.render('timesheet')
Every time I call: http://localhost:3000/api/tasks am getting a Cannot GET /api/tasks
My server.js
var express = require('express');
var path = require('path');
var BodyParser = require('body-parser');
var index = require('./routes/index');
var tasks = require('./routes/tasks');
var port = 3000;
var app = express();
//View Engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
// Set Static Folder
app.use(express.static(path.join(__dirname, 'client')));
// Body Parser MW
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({extended: false}));
app.use('/', index);
app.use('api', tasks);
app.listen(port, function(){
console.log('Server started on port '+port);
});
I am still learning the ropes. Thank you in advance
tasks.js
var express = require('express');
var app= express();
var mongojs = require('mongojs')
var db = mongojs('mongodb://<user>.:<****>#ds125365.mlab.com:25365/mytasklist_wafalme', ['tasks'])
// Get All Tasks
app.get('/tasks', function(req, res, next){
db.tasks.find(function(err, tasks){
if(err){
res.send(err);
}
res.json(tasks);
});
});
// Get Single Tasks
app.get('/tasks/:id', function(req, res, next){
db.tasks.findOne({_id: mangojs.ObjectId(req.params.id)}, function(err, task){
if(err){
res.send(err);
}
res.json(task);
});
});
module.exports = app;
I have attached the task.js file that runs in the routes folder with the index.js
Use an absolute route to define the API routing context:
app.use('/', index);
app.use('/api', tasks);
Always include a forward slash (/) at the beginning of your routes.
I'm trying to implement my own helper for Handlerbars but i cannot figure out where i need to register it so I can access it inside my template.
I always get Missing helper: "abcde"
I've checked many of the same questions on here having the same issue but with no success.
Here's my app.js :
var express = require('express');
var handlebars = require('handlebars');
var expresshandlebars = require('express-handlebars');
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 app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', expresshandlebars({ defaultLayout: 'main', layoutsDir: path.join(__dirname, 'views/layouts') }));
app.set('view engine', 'handlebars');
handlebars.registerHelper('abcde',
function (str) {
return str;
}
);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '../../site')));
app.use('/', index);
// 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;
Here's how i use the template inside my main.handlebars layout file:
{{abcde "test"}}
Did you try this technique? From here https://www.npmjs.com/package/express-handlebars
var express = require('express');
var exphbs = require('express-handlebars');
var app = express();
var hbs = exphbs.create({
// Specify helpers which are only registered on this instance.
helpers: {
foo: function () { return 'FOO!'; },
bar: function () { return 'BAR!'; }
}
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
Either way, I would focus on setting the helper on your expresshandlebars, and not your handlebars variable.
Unable to load the webpage because the server sent no data.
Error code: ERR_EMPTY_RESPONSE
My local NodeJS setup becomes intermittently becomes unresponsive . When I refresh my computer it works fine but it keeps giving me the following message. Does anything in my code scream WRONG.
//dependencies
var path = require('path');
var express = require('express');
var http = require('http');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var schemas = require('./schemas/schemas');
//main config
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('view options', {
layout: false
});
app.use(express.logger());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('BodySnatchingLizardPPL'));
app.use(express.session());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.configure('development', function () {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
app.configure('production', function () {
app.use(express.errorHandler());
});
//passport config
var Account = require('./models/account');
passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());
//mongoose
mongoose.connect('mongodb://demo2:demo2#ds033699.mongolab.com:33699/nicksdbthing');
require("fs").readdirSync("./routes_data_get/").forEach(function(file) {
require("./routes_data_get/" + file)(app);
});
require("fs").readdirSync("./routes_data_post/").forEach(function(file) {
require("./routes_data_post/" + file)(app);
});
require("fs").readdirSync("./routes_data_post/").forEach(function(file) {
require("./routes_data_post/" + file)(app);
});
app.listen(app.get('port'), function () {
console.log(("Express server listening on port " + app.get('port')))
});
I am trying to add in a subdomain with node.sj and Expressjs v3, but I keep getting 404 cannot get / when trying to load the subdomain.
var express = require('express'),
app = module.exports = express(),
MongoStore = require('connect-mongodb'),
server = require('http').createServer(app),
fs = require('fs'),
socket = require('./lib/sockets'),
flash = require('./middleware/flash');
app.configure('development', function () {
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function () {
app.use(express.errorHandler());
});
app.configure(function () {
app.use(express.favicon(__dirname + '/public/domain.com/images/favicon.ico'));
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views/site');
app.set('view engine', 'ejs');
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(flash());
app.use(app.router);
app.use(express.vhost(app.get('manager_vhost'), require('./subdomains/Manager')));
});
server.listen(3000);
socket.listen(server, sessionStore, app);
This is what I have in my Manager file
var express = require('express'),
manager = module.exports = express();
manager.configure(function () {
manager.use(express.static(manager.get('base_location') + '/public/'));
manager.engine('.html', require('ejs').__express);
manager.set('view engine', 'ejs');
manager.set('version', version);
});
Is there something I am doing wrong here?
Where are your routes defined? Try adding in a route and see what happens
manager.get('/', function (req, res) {
res.render('layout', {
title: 'Manager '
});
});