Express displaying mongodb documents in Jade - node.js

I'm learning Node, Express, Jade & Mongodb. I'm unable to display my mongodb documents in jade. I'm unable to figure it out on my own. I'm successfully logging all documents using console.log and it display all the documents correctly. Please no mongoose or other solutions. Just how to build on this code. I already connected to the db, displayed all documents in terminal. How to be able to pass it to Jade and display it in view.jade?
Thanks.
Here is my app.js code
var express = require('express');
var app = express();
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// Mongodb Example http://www.guru99.com/node-js-mongodb.html
var MongoClient = require('mongodb').MongoClient
var url = 'mongodb://localhost/EmployeeDB';
MongoClient.connect(url, function(err, db) {
//Insert data into mongodb db. If the collection doesn't exist, it will be created with the first inserted document
db.collection('employee').insertOne({
number : 17,
name: "aaa"
});
//Updating Documents in a collection
db.collection('employee').updateOne(
{"name": "New Employee"}, {$set: {"name": "AA"}}
);
//Deleting Documents in a collection
db.collection('employee').deleteOne(
{ "name": "name" }
);
// no need to pass a second parameter. Just the name of the field to be deleted.
//Querying for data in mongodb db .
var cursor = db.collection('employee').find();
cursor.each(function (err, doc) {
//console.log(doc)
});
console.log("connected");
db.close();
});
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(require('stylus').middleware(path.join(__dirname, 'public')));
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;
Here is my index.js
var express = require('express');
var router = express.Router()
//the global str variable is accessable from anywhere and logging the db.collection but how I pass it to jade?
var str = "";
/* GET home page. and iterate, display the collection to console log. */
router.get('/', function (req, res) {
var MongoClient = require('mongodb').MongoClient
var url = 'mongodb://localhost/EmployeeDB';
MongoClient.connect(url, function (err, db) {
var str = db.collection('employee').find();
str.each(function (err, doc) {
console.log(doc);
});
//How to pass the .db.collection documents to Jade?
res.render('index');
});
});
Here is my index.jade file
extends layout
block content
h1= title

https://naltatis.github.io/jade-syntax-docs/ Has useful information for view.jade files
index.js needs an array to hold the mongo results:
var results_from_mongo = [];
and everytime we get a result from the query, let's push it onto the array (array language for "insert an element into the array")
results_from_mongo.push(doc); //Push result onto results_array
then we must simply send it along to res.render:
res.render('index', {"results": results_from_mongo });
So in your index.js file
/* GET home page. and iterate, display the collection to console log. */
router.get('/', function (req, res) {
var MongoClient = require('mongodb').MongoClient
var url = 'mongodb://localhost/EmployeeDB';
var results_from_mongo = [];
MongoClient.connect(url, function (err, db) {
var str = db.collection('employee').find();
str.each(function (err, doc) {
console.log(doc);
results_from_mongo.push(doc); //Push result onto results_array
});
//now we have a results array filled like this:
// results_from_mongo = ["some string", "some string", "some string"]
//so let's pass them to the jade file to render them.
res.render('index', {"results": results_from_mongo });
//this will pass the data in JSON format to the JADE file called 'index' (index.jade)
The data at this point looks like
{ "results" : ["some string", "some string", "some string"] }
and in index.jade we can do something like
extends layout
block content
h1= title
h2= "results from mongo:"
select
each mongo_result, i in results
div Result #{i} #{mongo_result}

The jade (now pug) file needs to be set up to show a table, if you want to send an array from the database to be displayed as html. Here is the relevent code that I use for my table layout in a sample index.pug file.
table
thead
tr
th Flight Date
th Tail Number
th Origin
th Destination
th Dep
th Arr
tbody
each mongo_result, i in results
tr
td= mongo_result.flight_date
td= mongo_result.tail_num
td= mongo_result.origin_airport_code
td= mongo_result.dest_airport_code
td= mongo_result.dep_time
td= mongo_result.arr_time
In this example, under the table header thead, I am setting up the captions for the header row of the table. Then under tbody, I am specifying the actual data I want pug to pull from each row of the array that is pushed to it. Pug is very sensitive to indentation with white space characters: it requires it. So you need to pay close attention to indentation or the results won't work as expected.

You can use the db() method to handle the collection:
var data = [];
router.get('/', function (req, res) {
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/'; // do not put db in url, EmployeeDB
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("EmployeeDB");
dbo.collection("employee").find({}).toArray(function(err, result) {
if (err) throw err;
data = result;
db.close();
});
});
res.render('index',{ data_employee : data });
});
});
And you must update your index.jade (or index.pug) file:
extends layout
block content
div.main
table
thead
tr
th name
th surname
tbody
each data in data_employee
tr
td= data.name
td= data.surname

Related

Getting duplicate results on Express API endpoint. How do I reset the search so that I get new results each time?

I'm using Express to create an endpoint so that I can access it with API calls. When I do the search the first time, everything works great, but if I do it again, I get the results from the previous time PLUS the results from the new search. How do I get the search results to reset each time?
Here is a link to the actual endpoint: (change out the word "covid" for any search term you like and if you do it atleast twice, you will see data from your last search displayed even after you have done a new search)
https://laffy.herokuapp.com/search/covid
Thanks so much for any help you can offer!
This is the app.js file which calls the twitterRouter and with app.use creates the endpoint at /search/:searchTerm:
app.js
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const indexRouter = require('./routes/index');
const twitterRouter = require('./routes/twitterCall.js');
const top20 = require('./routes/twitterTop20.js');
const app = express();
app.set('views', path.join(__dirname, 'views'));
// app.set('port', process.env.PORT || 3001);
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
//creates route to use search at /search/
app.use('/search/:searchTerm', twitterRouter.search);
//creates route to access to get the top 20 Twitter hashtags trending
app.use('/top20', top20);
// 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;
I was under the impression that using res.send() ends the API search, but it doesn't seem to end.
Then here is the actual API call and where it generates the data for the endpoint:
twitterCall.js
//twitter file that searchs for tweets specified in params.q
var Twitter = require('twitter');
var config = require('../config/config.js');
var express = require('express');
var router = express.Router();
var T = new Twitter(config);
var locationsToSend = [];
exports.search = (req, res) => {
if (req.body == null) {
res.status(404).send( {
message: "Search can not be blank"
})
}
var params = {
q: req.params.searchTerm,
count: 1000,
result_type: 'recent',
lang: 'en'
}
//Initiate your search using the above parameters
T.get('search/tweets', params, function(err, data, response) {
//if there is no error, proceed
if(!err){
// Loop through the returned tweets
for(let i = 0; i < data.statuses.length; i++){
if (data.statuses[i].user.location!==null && data.statuses[i].user.location!=="") {
locationsToSend.push({
id: data.statuses[i].id_str,
createdAt: data.statuses[i].created_at,
text: data.statuses[i].text,
name: data.statuses[i].user.screen_name,
location: data.statuses[i].user.location
});
}
}
res.send(locationsToSend);
} else {
console.log(err);
return res.status(404).send({
message: "error searching " + err
});
}
});
};
Your locationsToSend variable is in global scope which is persisted as long as your express app is running. You should initialize that variable inside the search/tweets callback and you'll get the behavior you want. That way each request will get its own locationsToSend to work with rather than the global one.

NodeJS image not uploading and category name showing variable instead of value

I am working on a NodeJS style blog and for some reason, the variable for the category name shows up as #{category.name} whereas the other variable values actually show the values. Secondly, When I submit the image for the post, it does not upload the image. Any help to see if there might be some errors in my code would be greatly appreciated. Thank you in advance.
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 session = require("express-session");
var multer = require("multer");
var upload = multer({ dest: "./public/images" });
var expressValidator = require("express-validator");
var mongo = require("mongodb");
var db = require("monk")("localhost/nodeblog");
var routes = require("./routes/index");
var posts = require("./routes/posts");
var categories = require("./routes/categories");
var app = express();
app.locals.moment = require("moment");
app.locals.truncateText = function(text, length) {
var truncatedText = text.substring(0, length);
return truncatedText;
};
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
// 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")));
// Express Session
app.use(
session({
secret: "secret",
saveUninitialized: true,
resave: true
})
);
// Express Validator
app.use(
expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split("."),
root = namespace.shift(),
formParam = root;
while (namespace.length) {
formParam += "[" + namespace.shift() + "]";
}
return {
param: formParam,
msg: msg,
value: value
};
}
})
);
// Connect-Flash
app.use(require("connect-flash")());
app.use(function(req, res, next) {
res.locals.messages = require("express-messages")(req, res);
next();
});
// Make our db accessible to our router
app.use(function(req, res, next) {
req.db = db;
next();
});
app.use("/", routes);
app.use("/posts", posts);
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;
index.pug
extends layout
block content
if posts
each post, i in posts
.post
h1
a(href='/posts/show/#{post._id}')
=post.title
p.meta Posted in
a(href='/categories/show/#{post.category}') #{post.category} by #{post.author} on #{moment(post.date).format("MM-DD-YYYY")}
img(src='/images/#{post.mainimage}')
!=truncateText(post.body,400)
a.more(href='/posts/show/#{post._id}') Read More
addpost.pug
extends layout
block content
h1=title
ul.errors
if errors
each error, i in errors
li.alert.alert-danger #{error.msg}
form(method='post', action='/posts/add', enctype="multipart/form-data")
.form-group
label Title:
input.form-control(name='title', type='text')
.form-group
label Category
select.form-control(name='category')
each category, i in categories
option(value='#{category.name}') #{category.name}
.form-group
label Body
textarea.form-control(name='body', id='body')
.form-group
label Main Image:
input.form-control(name='mainimage', type='file')
.form-group
label Author:
select.form-control(name='author')
option(value='Erik Robles') Erik Robles
option(value='John Doe') John Doe
input.btn.btn-default(name='submit',type='submit',value='Save')
script(src='/ckeditor/ckeditor.js')
script
| CKEDITOR.replace('body');
addcategory.pug
extends layout
block content
h1=title
ul.errors
if errors
each error, i in errors
li.alert.alert-danger #{error.msg}
form(method='post', action='/categories/add')
.form-group
label Name:
input.form-control(name='name', type='text')
input.btn.btn-default(name='submit',type='submit',value='Save')
posts.js
var express = require("express");
var router = express.Router();
var multer = require("multer");
var upload = multer({ dest: "./public/images" });
var mongo = require("mongodb");
var db = require("monk")("localhost/nodeblog");
router.get("/add", function(req, res, next) {
var categories = db.get("categories");
categories.find({}, {}, function(err, categories) {
res.render("addpost", {
title: "Add Post",
categories: categories
});
});
});
router.post("/add", upload.single("mainimage"), function(req, res, next) {
// Get Form Values
var title = req.body.title;
var category = req.body.category;
var body = req.body.body;
var author = req.body.author;
var date = new Date();
// Check Image Upload
if (req.file) {
var mainimage = req.file.filename;
} else {
var mainimage = "noimage.jpg";
}
// Form Validation
req.checkBody("title", "Title field is required").notEmpty();
req.checkBody("body", "Body field is required").notEmpty();
// Check Errors
var errors = req.validationErrors();
if (errors) {
res.render("addpost", {
errors: errors
});
} else {
var posts = db.get("posts");
posts.insert(
{
title: title,
body: body,
category: category,
date: date,
author: author,
mainimage: mainimage
},
function(err, post) {
if (err) {
res.send(err);
} else {
req.flash("success", "Post Added");
res.location("/");
res.redirect("/");
}
}
);
}
});
module.exports = router;
index.js
var express = require("express");
var router = express.Router();
var mongo = require("mongodb");
var db = require("monk")("localhost/nodeblog");
/* GET home page. */
router.get("/", function(req, res, next) {
var db = req.db;
var posts = db.get("posts");
posts.find({}, {}, function(err, posts) {
res.render("index", { posts: posts });
});
});
module.exports = router;
categories.js
var express = require("express");
var router = express.Router();
var mongo = require("mongodb");
var db = require("monk")("localhost/nodeblog");
router.get("/show/:category", function(req, res, next) {
var posts = db.get("posts");
posts.find({ category: req.params.category }, {}, function(err, posts) {
res.render("index", {
title: req.params.category,
posts: posts
});
});
});
router.get("/add", function(req, res, next) {
res.render("addcategory", {
title: "Add Category"
});
});
router.post("/add", function(req, res, next) {
// Get Form Values
var name = req.body.name;
// Form Validation
req.checkBody("name", "Name field is required").notEmpty();
// Check Errors
var errors = req.validationErrors();
if (errors) {
res.render("addpost", {
errors: errors
});
} else {
var categories = db.get("categories");
categories.insert(
{
name: name
},
function(err, post) {
if (err) {
res.send(err);
} else {
req.flash("success", "Category Added");
res.location("/");
res.redirect("/");
}
}
);
}
});
module.exports = router;
If I am missing anything, please let me know so I can make the appropriate edits. Again, Thank you.
P.S. By structure is:
routes
categores.js
index.js
posts.js
views
addcategory.pug
addpost.pug
error.pug
index.pug
layout.pug
app.js
The code I was using is old (circa 2016) and no longer works. In calling the variable name, you must remove the curly braces, hash and quotes from the first option variable. Here is how the code should read in the categories options section:
addpost.pug
.form-group
label Category
select.form-control(name='category')
each category, i in categories
option(value=category.name) #{category.name}
I hope this answer helps someone struggling with the same issue.

display data from mongodb with webix

I'm new in javascript and I want to use webix.
I saw the get started and it's Ok...
So, my problem is that I can't display data from mongodb.
This is my server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
//connect to the mongo
var db = require('mongoskin').db("mongodb://localhost:27017/test", { w: 0});
db.bind('sites');
//create the app instance
var app = express();
//serve static files
app.use(express.static(path.join(__dirname, 'public')));
//parse POST data
app.use(bodyParser.urlencoded({ extended: false }));
// // parse application/json
app.use(bodyParser.json());
function after_update(err, res, record){
if (err){
res.status(500);
res.send({ error:err.toString() });
} else {
res.send(record || {});
}
}
//data loading
app.get('/data', function(req, res){
db.record.find().toArray(function(err, data){
for (var i = 0; i < data.length; i++){
data[i].id = data[i]._id;
delete data[i]._id;
}
res.send(data);
});
});
app.post('/data', function(req, res){
db.record.insert(req.body, function(err, record){
if (err) return res.send({ status:"error" });
res.send({ newid:req.body._id });
});
});
app.put('/data/:id', function(req, res){
db.record.updateById(req.param("id"), req.body, function(err){
if (err) return res.send({ status:"error" });
res.send({});
});
});
app.delete('/data/:id', function(req, res){
db.record.removeById(req.param("id"), req.body, function(err){
if (err) return res.send({ status:"error" });
res.send({});
});
});
app.listen(3000);
and I'm using index.html to display data. Here that it sucks.
my problem is that I can't found the right manner to get the data from my table in mongodb.
I want to display the cars in my DB.
who has an exemple that can help?
Anyone can help please?
Thank you
Try to load the "/data" in the browser. If it shows the valid JSON, check the client-side code of the datatable, it must be something like following
{ view:"datatable", autoConfig:true, url:"/data" }
I see 2 problems in your code (i guess that your collection is "cars" becouse your text):
You are binding a diferent collection than "cars", in the line "db.bind('sites');". You should change for "db.bind('cars');"
You are using the collection "record" to retrieve and write data, in the sentences "db.record.find", "db.record.insert", "db.record.updateById" and "db.record.removeById". You should change for "db.cars.find", "db.cars.insert", "db.cars.updateById" and "db.cars.removeById".
Cheers.

Bootstrap form sending data wrong to MongoDB database

I have a form I created using Twitter Bootstrap that's posting the data I put in it incorrectly to my MongoDB database. The model of the database is: ({date: 'date', link: 'string'}) and the result should look like this:
{ _id: 558a69c644c2a80985299594,
date: Mon Jul 03 1995 02:00:00 GMT+
link: 'https://www.youtu.be.com' },
But when I submit data from the form this is what I get instead:
{ _id: 558a69c644c2a80985299594,__v:0},
When I manually insert to the collection it seems to work, but I want to submit from the form.
Here is the code for the router where the POST action is handled:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
/* Database stuff */
//connect to the data store and the set up the database
var db = mongoose.connection;
//connect to the database
mongoose.connect('mongodb://localhost/Mandela_Diaries/data');
//Create a model which connects to the schema and entries collection in the Mandela_Diaries database
var Entry = mongoose.model("Entry", new Schema({date: 'date', link: 'string'}), "entries");
mongoose.connection.on("open", function() {
console.log("mongodb is connected!");
});
//The route for getting data for the database - GET form
router.get("/", function(req, res) {
//Send the current entries to the page
Entry.find({}, function(err, entries) {
console.log(entries);
if(err) {
res.status(404).json({"error": "not found", "err":err});
return;
} else {
//res.json(entries);
res.render('database', {title: 'database', entries: entries});
}
});
});
router.post('/', function(req, res) {
//console.log(date, link);
//res.redirect('form')
var newEntry = new Entry({entries: {'date': req.body.date, 'link': req.body.link}});
newEntry.save(function(err, entries){
//console.log(entries);
//res.redirect('form');
if (err !== null) {
res.status(500).json(err);
} else {
res.redirect('database');
};
});
});
module.exports = router;
And here is the code for the form which is written using the Jade template:
extends layout
block content
.container
.row
.col-s-12
h1 The Mandela Diaries Database
.row
.col-s-4
h3 Add Entry
.row
.col-s-12
form.form-inline(method='post', action='/create')
.form-group
label(for='date') Date:
input#datepicker.form-control.datepicker(type='text', value='date')
.form-group
label(for='link') Link:
input#link.form-control(type='string', value='link')
button.btn.btn-default(type='submit') Submit
.row
p
| Format options:
br
select#format
option(value='mm/dd/yy') Default - mm/dd/yy
option(value='yy-mm-dd') ISO 8601 - yy-mm-dd
option(value='d M, y') Short - d M, y
option(value='d MM, y') Medium - d MM, y
option(value='DD, d MM, yy') Full - DD, d MM, yy
option(value="'day' d 'of' MM 'in the year' yy") With text - 'day' d 'of' MM 'in the year' yy
.row
#entries.col-s-12
ul
script(type'text/javascript', scrc='../public/js/script.js')
Please help as I am running out of time on this project.
The main app.js file is below:
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 database = require('./routes/database');
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('/public', express.static(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
app.use('public/js', express.static(path.join(__dirname + 'public/js')));
app.use('public/css', express.static(path.join(__dirname + 'public/css')));
app.use('/', routes);
app.use('/users', users);
app.use('/database', database)
app.use('/create', database)
// 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;
app.listen(8080);
console.log("The server has started");
I think the problem is with your jade template. You're not specifying the name attribute to your input elements. Try adding them
input#link.form-control(type='string', name='link')
and
input#datepicker.form-control.datepicker(type='text', name='date')
Edit:
In your post route, try changing the relevant line to this var newEntry = new Entry(req.body);

Display basic HTML file in NodeJS and ExpressJS

I am using NodeJS and ExpressJS to implement a RESTful API server for a simple backend. I am also using BackboneJS to render views in the front. Therefore, right now I have a single index.html file that I want to render when the client sends a /GET to the '/' route. This is what I have so far:
var express = require('express');
var app = express();
app.use(express.bodyParser());
var mongo = require('mongodb');
var mongoose = require('mongoose');
var Server = mongo.Server,
DB = mongo.Db,
BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new DB('mydb', server, {safe: true});
db.open(function(err, db) {
if(!err) {
console.log("Connected to 'mydb' database");
db.collection('items', {safe:true}, function(err, collection) {
if (err) {
console.log("Creating collection 'items'");
}
});
}
});
var port = process.env.PORT || 3000;
app.engine('.html');
var listItems = function(req, res){
db.collection('items', function(err, collection){
var items = collection.find();
console.log(items);
res.send(items);
});
}
var itemDetails = function(req, res){
}
var deleteItem = function(req, res){
}
var createItem = function(req, res){
}
var updateItem = function(req, res){
}
var routeHome = function(req, res){
// What can I do here to render a plain .html file?
}
app.all('*', function(req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Content-Type", "application/json");
next();
});
app.get('/', routeHome);
app.get('/items', listItems);
app.get('/items/:id', itemDetails);
app.del('/users/:id', deleteItem);
app.post('/users', createItem);
app.put('/users/:id', updateItem);
app.listen(port);
console.log("Server started up on port " + port);
As you can see I have everything set up except I cannot figure out how to send a regular .html file to the client. I do not need a rendering engine because Backbone is doing all that for me. I just want to get index.html to go to the client.
How about just using the express.static middleware? Since you're using Backbone, you might have the need for sending static JS files as well:
app.use(express.static(__dirname));
Place that somewhere before your other routes. It will try and find files requested in __dirname (the directory where your app.js file resides, but you can of course change the location where the middleware will try and find files), including index.html.
Step One, Remove app.engine(".html"),
Step Two:
var routeHome = function(req, res){
// Do What Ever
res.sendFile("index.html",function(err){ // Transfer The File With COntent Type Text/HTML
if(err){
res.end("Sorry, Error.");
}else{
res.end(); // Send The Response
}
})
}

Resources