This app works fine locally and works on openshift with no errors, however the views aren't rendering it is just printing the source code. I tried deleting and recreating the app but still no luck.
Here is part of my server.js file:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var fs = require("fs");
var handlebars = require("handlebars");
var WebPageTest = require('webpagetest');
// Web Page Test - API key.
var wpt = new WebPageTest('www.webpagetest.org', '1234567890');
var router = express.Router();
app.use("/css", express.static(__dirname + '/css'));
app.use("/js", express.static(__dirname + '/js'));
app.use("/img", express.static(__dirname + '/img'));
/***** Views *****/
// Homepage.
app.get('/', function(req, res) {
var template = fs.readFileSync("views/index.html", "utf8");
// handlebars data, optional.
var source = {
message : "Homepage!"
};
var pageBuilder = handlebars.compile(template);
var pageText = pageBuilder(source);
res.writeHead(200, {"Context-Type": "text/html"});
res.write(pageText);
res.end();
});
/***** Start App *****/
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 5000;
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
app.listen(server_port, server_ip_address, function(){
console.log("Listening on " + server_ip_address + ", server_port " + server_port);
});
Here is part of the package.json
{
"name": "wpt",
"version": "1.0.0",
"description": "",
"main": "server.js",
"dependencies": {
"body-parser": "^1.10.0",
"express": "^4.10.6",
"webpagetest": "^0.3.1",
"mongoose": "^3.8.21",
"handlebars": "^2.0.0",
"express3-handlebars": "^0.5.2",
"fs":"*"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
I added fs to the dependencies manually but it didn't seem to have any effect.
It's probably a lot easier to just use a handlebars Express views engine such as hbs. Example:
// ...
var hbs = require('hbs');
app.engine('hbs', hbs.__express);
app.engine('html', hbs.__express);
app.set('view engine', 'hbs');
app.set('views', __dirname + '/views');
hbs.localsAsTemplateData(app);
app.get('/', function(req, res) {
res.render('index.html', {
message: 'Homepage!'
});
});
// ...
Related
Getting a Strange Error I have tried Everything but My code Doest not pick up Req.file..
I AM new to Nodejs And Express, AND i was try to upload an image using multer.
Req.file is showing UNDEFINED and Image is not uploading
This is my source code with using PUG(template engine)
Bumper.pug
extends base.pug
block style
style
include ../static/productUpload.css
block scripts
script(src="../static/categorienav.js")
//- script(src="../static/productid.js")
block content
p.heading
| Upload BUMPER
.UploadPage
.Uploadinfo
p#PID BUMPER
form.uploadform(action=`/BumperUpload` , method="post" enctype="multipart/form-data")
input.catsclass(type="file",name="file" accept="image/*" required)
input.catsclass(type="text",name="Link",placeholder="paste Link here" required)
input.catsclass(type="submit")
| #{Change}
Bumper.js
var express = require('express');
var myrouter= express.Router();
var bodyparser = require('body-parser');
var fs = require('fs');
var multer = require('multer');
// Initialize the express object
var app = express();
// Use body-parser to parse incoming data
app.use(bodyparser.urlencoded({extended : true}))
app.set('view engine', 'pug') // Set the template engine as pug
app.set('views', [__dirname + '/views', __dirname + '/views2']); // Set the views directory
myrouter.get('/BumperUpload',(req,res)=>{
res.render('Bumper.pug');
})
var storage = multer.diskStorage({
destination: function (request, file, callback) {
callback(null, './uploads/');
},
filename: function (request, file, callback) {
console.log(file);
callback(null, file.originalname)
}
});
var upload = multer({ storage: storage });
myrouter.post('/BumperUpload', upload.single('file'), function (req, res) {
console.log(req.file);
if (req.file) {
console.log('Uploading File');
var profileImageOriginlName=req.file.originalname;
var profileImageName=req.file.name;
var profileImageMime=req.file.mimetype;
var profileImagePath=req.file.path;
var profileImageExt=req.file.extension;
var profileImageSize=req.file.size;
}
else
{
var profileImageName='noimage.png';
}
console.log(profileImageName);
res.send("done")
});
module.exports = myrouter;
Index.js
const express = require("express");
const path = require("path");
const fs = require("fs");
const app = express();
const port = 80;
const bodyparser = require('body-parser')
// var http = require('http');
const fileUpload = require('express-fileupload');
var nodemailer = require('nodemailer');
// var mail = require("./static/mail.js")
//////mongojson = require("./mongodb.js")
var domain = require("domain").create();
var mongoose = require('mongoose');
var HOME = require('./models/HOME/HOME.js')
var Bumper = require('./models/HOME/Bumper.js');
var MongoClient = require('mongodb').MongoClient;
app.use('/static', express.static('static')) // For serving static files
app.use(express.urlencoded());
app.use(fileUpload());
// PUG SPECIFIC STUFF
app.set('view engine', 'pug') // Set the template engine as pug
app.set('views', [__dirname + '/views', __dirname + '/views2']); // Set the views directory
app.use('/', Bumper);
// START THE SERVER
app.listen(port, () => {
// //console.log(res);
//console.log(`The application started successfully on port ${port}`);
});
package.json
{
"name": "rk",
"version": "1.0.0",
"description": "",
"main": "param.js",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"bootstrap-icons": "^1.1.0",
"connect-busboy": "0.0.2",
"connect-flash": "^0.1.1",
"cookie-parser": "^1.4.5",
"crypto": "^1.0.1",
"domain": "0.0.1",
"express": "^4.17.1",
"express-fileupload": "^1.2.0",
"express-session": "^1.17.1",
"filesystem": "^1.0.1",
"formidable": "^1.2.2",
"jquery": "^3.5.1",
"jsonwebtoken": "^8.5.1",
"localStorage": "^1.0.4",
"method-override": "^3.0.0",
"mongodb": "^3.6.3",
"mongoose": "^5.10.14",
"multer": "^1.4.2",
"nodemailer": "^6.4.16",
"passport": "^0.4.1",
"passport-local": "^1.0.0",
"pug": "^3.0.0"
},
"devDependencies": {},
"scripts": {
"start": "nodemon param.js"
},
"author": "RISHABH GARG",
"license": "ISC"
}
Result:
Database Connected <br>
undefined // req.file is showing undefined<br>
noimage.png //image is not upload<br>
Hey I got the solution I Uninstall the Express-FileUpload and now it works
I'm currently trying to learn MEAN stack. The tutorial are about a task manager. Right now I'm trying to connect to mongodb atlas to retrieve sample data in database but they are not showing up http://localhost:3000/api/tasks
Here is my tasks.js file
var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs('drivers',['tasks']);
router.get('/tasks', function(req, res, next){
db.tasks.find(function(err, tasks){
if(err){
res.send(err);
}
res.json(tasks);
});
});
module.exports = router;
Here is my server.js file
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var task = require('./routes/tasks');
var app = express();
var port = 3000;
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'client')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', index);
app.use('/api', task);
app.listen(port, function(){
console.log('Server started on port' +port);
});
Here is my package.json file
{
"name": "mytasklist",
"version": "1.0.0",
"description": "Task Manager",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"ejs": "^2.6.1",
"express": "^4.17.1",
"mongojs": "^2.6.0"
}
}
Problem solved, I pasted the wrong version for my nodejs driver.
need to use mongojs version 3.0.0 to connect to atlas
Given is:
/routes/index.js
var express = require('express');
var router = express.Router();
//var mongo = require('mongodb').MongoClient;
//var objectId = require('mongodb').ObjectID;
var mongo = require('mongodb');
var assert = require('assert');
var url = 'mongodb://localhost:27017/test';
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
router.post('/insert', function(req, res, next) {
var item = {
title: req.body.title,
content: req.body.content,
author: req.body.author
};
mongo.connect(url, function(err, db) {
assert.equal(null, err);
db.collection('userdata').insertOne(item, function(err, result) {
assert.equal(null, err);
console.log('Item inserted');
db.close();
});
});
res.redirect('/');
});
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 hbs = require('express-handlebars');
var expressValidator = require('express-validator');
var expressSession = require('express-session');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.engine('hbs', hbs({extname: 'hbs', defaultLayout: 'layout', layoutsDir: __dirname + '/views/layouts/'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public'))); eingetragen)
app.use(expressValidator());
app.use(express.static(path.join(__dirname, 'public')));
app.use(expressSession({secret: "eefa56_50cacb_34634f", saveUninitialized: false, resave: false})); // dafault storage is RAM, otherwise kann ich in der API von express-session rumwühlen, da der storage serverseitig in einer DB erfolgt
app.use('/', indexRouter);
app.use('/users', usersRouter);
...
package.json
{
"name": "sample_express_app(POST_GET_handlebars)",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"assert": "^1.4.1",
"body-parser": "^1.18.3",
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"express": "~4.16.0",
"express-handlenter": "^3.0.0",
"express-session": "^1.15.6",
"express-validator": "^5.3.0",
"http-errors": "~1.6.2",
"mongodb": "^3.1.4",
"morgan": "~1.9.0"
}
}
The mongoDB server is running and there is no issue to manipulate the database in the CMD. It especially deals with the router.post('/insert' ... in /routes/index.js. There is something wrong(but maybe at another point too).
I also tried it with this (either I get the error db.collection('userdata').insert(... --> 'db.collection is not a function' or db.userdata.insert(... --> 'cannot read property insert'):
1)
db.runCommand({
insert: "userdata",
documents: [ item ]
}
)
2)
db.collection('userdata').insertOne(item, function(err, result) {
assert.equal(null, err);
console.log('Item inserted');
db.close();
});
3)
db.userdata.insert(item, function(err, result) {
assert.equal(null, err);
console.log('Item inserted');
db.close();
});
Native mongoDB driver works with the help of MongoClient.
Make changes in the index.js file
var mongo = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017';
mongo.connect(url, function(err, client) {
const db = client.db(dbName);
//your db queries
})
refer mongodb
Iam getting following error if I try to open the localhost:3000 or localhost:3000/login. Can someone help me what is the problem? It is very strange. Many thanks
My Code
var express = require('express');
var crypto = require('crypto');
var bodyParser = require('body-parser');
var flash = require('connect-flash');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var path = require ('path');
var port = process.env.PORT || 3000;
var MongoClient = require('mongodb').MongoClient,
ObjectID = require('mongodb').ObjectID,
url = require('url');
var db;
//var mongo;
//var collection;
//dataExt = require('./routes/serverExtend');
// setup middleware
var app = express();
app.use(bodyParser());
app.use(flash());
app.use(cookieParser('secret'));
app.use(session({cookie: { secret: 'keyboard cat', maxAge: 60000 }}));
app.use(express.static(__dirname + 'public')); //setup static public directory
app.set('views', __dirname + 'testapp/views'); //optional since express defaults to CWD/views
app.set('view engine', 'ejs');
// Start server
app.listen(port);
console.log('App started on port ' + port);
// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/testDB", function(err, database) { //"mongodb://localhost:27017/test"
if(err) throw err;
db = database;
});
app.get('/', function(req, res) {
res.render('index.ejs', { message: req.flash('signupMessage')}); // load the index.ejs file
app.get('/login', function(req, res) {
res.render('login.ejs');
});
Here is my package.json
{
"name": "NodejsStarterApp",
"version": "0.0.1",
"description": "A sample nodejs"
"dependencies": {
"express" : "~4.0.0",
"ejs" : "*",
"mongodb":"*",
"connect-flash" : "~0.1.1",
"morgan": "~1.0.0",
"body-parser": "*",
"cookie-parser": "~1.0.0",
"express-session": "~1.0.0"
},
"engines": {
"node": "0.10.26"
},
"repository": {}
}
Here is the problem.
change this line
app.set('views', __dirname + 'testapp/views');
to
app.set('views', __dirname + 'views');
Because when you say just __dirname + 'views' it looks in {appName}/views/fileToRender. But because you are saying __dirname + 'testapp/views' it will search {appName}/testapp/views/fileToRender.
I am using dustjs as the templating engine in an express app, and was wondering if anyone has successfully used the contextDump helper in a server side template in express? I followed the consolidate example for integrating dust with express, and it is working well. The helpers are there, as I'm able to do a simple test with the eq helper and it works. but when trying to dump the context I'm not seeing it anywhere. here is a sample template:
{>layout/}
{<content}
<ul>
{#users}
<li>{username} - Create New Task
<ul>
{#user.tasks}
<li>{title} - Delete Task |
Update Task</li>
{/user.tasks}
</ul>
</li>
{/users}
</ul>
{/content}
{#contextDump to="console"/}
Here's my app.js:
var express = require('express');
var app = express();
var http = require('http');
var path = require('path');
var db = require ('./models');
var dust = require('dustjs-linkedin');
var cons = require('consolidate');
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('models', db);
//configure dust
app.set('view engine', 'dust');
app.set('template_engine', 'dust');
app.engine('dust', cons.dust);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
//require routes
require('./routes')(app);
require('./routes/user')(app);
require('./routes/task')(app);
db
.sequelize
.sync({ force: true })
.complete(function (err) {
if (err) {
throw err;
} else {
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
}
});
and here's package.json:
{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "3.4.6",
"sequelize": "~2.0.0-beta.5",
"mysql": "~2.0.0-rc2",
"lodash": "~2.4.1",
"async": "~0.2.9",
"dustjs-linkedin": "~2.2.2",
"dustjs-helpers": "~1.1.1",
"consolidate": "~0.10.0"
}
}
Thanks!