Issue with express search function - javascript

So I am working on an api for a todo app, and I have my 4 basic functions implemented but I'm trying to implement a search function. It worked the first time I tested it, but now every time I attempt to use it I am returning the same task no matter what my query is. Any help would be great. Also my search function is in my app.js file because I couldn't get it to function properly in my tasks.js file.
App.js
var express = require('express'),
routes = require('./routes'),
http = require('http'),
tasks = require('./routes/tasks'),
mongoose = require('mongoose'),
task = require('./routes/search');
var Task = require('./models/task').Task;
// MongoDB Connection
mongoose.connect('mongodb://localhost/task_tracker');
var app = express();
app.configure(function() {
app.set('port', 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.urlencoded());
app.use(express.json());
});
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/', routes.index);
app.get('/tasks', tasks.index);
//app.get('/search', tasks.FindByQuery);
//app.get('/tasks/:task.:name?', task.FindByQuery);
app.get('/search', function(req, res) {
var query = req.query
//res.send(query['name']);
Task.findOne(query['name'], function(err, doc) {
if(!err && doc) {
res.json(200, doc);
} else if(err) {
res.json(500, { message: "Error loading task." + err});
} else {
res.json(404, { message: "Task not found."});
}
});
//res.end(JSON.stringify(query));
});
app.get('/tasks/:id', tasks.show);
app.post('/tasks', tasks.create);
app.put('/tasks', tasks.update);
app.del('/tasks', tasks.delete);
http.createServer(app).listen(app.get('port'), function() {
console.log("Express server listening on port 3000");
});
Tasks.js
var Task = require('../models/task').Task;
/*
* Tasks Routes
*/
exports.index = function(req, res) {
Task.find({}, function(err, docs) {
if(!err) {
res.json(200, { tasks: docs });
} else {
res.json(500, { message: err });
}
});
}
exports.show = function(req, res) {
var id = req.params.id;
Task.findById(id, function(err, doc) {
if(!err && doc) {
res.json(200, doc);
} else if(err) {
res.json(500, { message: "Error loading task." + err});
} else {
res.json(404, { message: "Task not found."});
}
});
}
exports.create = function(req, res) {
var task_name = req.body.task_name; // Name of task.
var description = req.body.task_description; // Description of the task
//Task.findOne({ name: task_name }, function(err, doc) { // This line is case sensitive.
Task.findOne({ name: { $regex: new RegExp(task_name, "i") } }, function(err, doc) { // Using RegEx - search is case insensitive
if(!err && !doc) {
var newTask = new Task();
newTask.name = task_name;
newTask.description = description;
newTask.save(function(err) {
if(!err) {
res.json(201, {message: "Task created with name: " + newTask.name });
} else {
res.json(500, {message: "Could not create task. Error: " + err});
}
});
} else if(!err) {
// User is trying to create a task with a name that already exists.
res.json(403, {message: "Task with that name already exists, please update instead of create or create a new task with a different name."});
} else {
res.json(500, { message: err});
}
});
}
exports.update = function(req, res) {
var id = req.body.id;
var task_name = req.body.task_name;
var task_description = req.body.task_description;
Task.findById(id, function(err, doc) {
if(!err && doc) {
doc.name = task_name;
doc.description = task_description;
doc.save(function(err) {
if(!err) {
res.json(200, {message: "Task updated: " + task_name});
} else {
res.json(500, {message: "Could not update task. " + err});
}
});
} else if(!err) {
res.json(404, { message: "Could not find task."});
} else {
res.json(500, { message: "Could not update task." + err});
}
});
}
exports.delete = function(req, res) {
var id = req.body.id;
Task.findById(id, function(err, doc) {
if(!err && doc) {
doc.remove();
res.json(200, { message: "Task removed."});
} else if(!err) {
res.json(404, { message: "Could not find task."});
} else {
res.json(403, {message: "Could not delete task. " + err });
}
});
}
search.js
var Task = require('../models/task').Task;
exports.FindByQuery = function(req, res) {
var query = req.query
//res.send(query['name']);
Task.findOne(query['name'], function(err, doc) {
if(!err && doc) {
res.json(200, doc);
} else if(err) {
res.json(500, { message: "Error loading task." + err});
} else {
res.json(404, { message: "Task not found."});
}
});
//res.end(JSON.stringify(query));
});
task.js
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
var taskSchema = new Schema({
name : { type: String, required: true, trim: true, index: { unique: true } }
, description : { type: String, required: true }
, date_created : { type: Date, required: true, default: Date.now }
});
var task = mongoose.model('task', taskSchema);
module.exports = {
Task: task
};

I ended up figuring it out I just had to change my function a little bit. My error was in the format of my findOne function.
app.get('/search', function(req, res) {
var query = req.query
//res.send(query['name']);
Task.findOne({name: query['name']}, function(err, doc) {
if(!err && doc) {
res.json(200, doc);
} else if(err) {
res.json(500, { message: "Error loading task." + err});
} else {
res.json(404, { message: "Task not found."});
}
});
//res.end(JSON.stringify(query));
});

Related

Node error handler bugs when using error pattern (err, req, res, next)

I am currently running node with the express middleware and handling request with the GET method. Errors like 404s or 500s are handled at the end of my script, after the GET method, but so far I have not been able to use Node's standard error handling method with err,req,res,next. The below code works fine for me. But ...
server.js
...
// Routing
app.use('/', function (req, res, next) {
req.const = {
nonce: nonce,
publicRoot: publicRoot,
client: client,
cachelifespan: cachelifespan
};
next();
}, router);
// Error handling
app.use('/', function (req, res, next) {
req.const = {
nonce: nonce,
publicRoot: publicRoot,
};
next();
}, errorHandler);
...
errorhandler.js:
...
errorHandler.use(function (req, res) {
let id = req.ip;
let url = req.url;
// Import
let nonce = req.const.nonce;
let publicRoot = req.const.publicRoot;
res.statusCode = 500;
let status = res.statusCode;
try {
let localPath = path.join(publicRoot, req.path);
fs.accessSync(localPath);
} catch (err) {
status = 404;
};
if (req.accepts('html')) {
try {
res.render('system/error', { title: status.toString(), description: 'This is an error!', nonce: 'nonceValue' }, function(err, html) {
html = html.replace("nonceValue", nonce);
res.send(html);
});
} catch (err) {
logError(id, status, req.url, err)
};
} else if (req.accepts('json')) {
res.send({ error: status.toString() });
} else {
res.type('txt').send("error: " + status.toString());
}
logError(id, status, req.url);
});
...
... if I try to write the app.use function to ...
app.use(function (err, req, res, next) {
... it bugs and Node's default error handler takes over.
I am not entirely sure how to fix that.
Or if I am doing the error handling right?
Any suggestions?
I found a solution to my problem.
Inside server.js (the main app js), I load the errorHandler in the beginning of the file:
const errorHandler = require('./errorhandler');
And in the last step, after the basic routing, I added the errorhandler:
// Routing
app.use('/', function (req, res, next) {
req.const = {
nonce: nonce,
publicRoot: publicRoot,
client: client,
cachelifespan: cachelifespan
};
next();
}, router);
// Error handling
app.use('/', function (req, res, next) {
req.const = {
nonce: nonce,
publicRoot: publicRoot,
};
next();
}, errorHandler);
Inside the separate errorhandler file:
//--------------------
// NODE
//--------------------
const express = require('express');
const errorHandler = express.Router();
//--------------------
// LOGGING
//--------------------
const { getDate, logOutput, logError } = require('./logger');
//--------------------
// ROUTER
//--------------------
errorHandler.use(function (req, res) {
let id = req.ip;
let url = req.url;
// Import
let nonce = req.const.nonce;
let publicRoot = req.const.publicRoot;
// Cookies
let insultor = "Samuel L Jackson says";
let insults = ['Motherfucker!!!', 'Son_of_a_bitch!!!', 'Asshole!!!', 'Punkass_motherfucker!!!', 'Whiny_little_bitch!!!', 'You_deserve_to_die_and_I_hope_you_burn_in_hell!!!', 'Web_motherfucker_do_you_speak_it?'];
let number = Math.floor(Math.random() * insults.length);
let insulted = false;
for (let [key, value] of Object.entries(req.cookies)) {
if (key.toString() == insultor) {
value = value.toString() + "_-_" + insults[number];
res.cookie(insultor, value);
insulted = true;
}
}
if (!insulted) {
res.cookie(insultor, insults[number]);
}
res.statusCode = 500;
let status = res.statusCode;
try {
let localPath = path.join(publicRoot, req.path);
fs.accessSync(localPath);
} catch (err) {
status = 404;
};
if (req.accepts('html')) {
try {
res.render('system/error', { title: status.toString(), description: 'This is an error, Motherfucker!', nonce: 'nonceValue' }, function(err, html) {
html = html.replace("nonceValue", nonce);
res.send(html);
});
} catch (err) {
logError(id, status, req.url, err)
};
} else if (req.accepts('json')) {
res.send({ error: status.toString() });
} else {
res.type('txt').send("error: " + status.toString());
}
logError(id, status, req.url);
});
module.exports = errorHandler;

How to merge two files API (Node.js)

I am a node.js and MySQL beginner and I just started setting up and trying out some basic code.
I find these two APIs to practice, one is the API for the CRUD database, and the other is the API for judging user login / registration.I tried to merge the APIs of these two files, and the result was a problem. I think the current problem is the configuration file (conf.js).I plan to write a function and then wrap any file and use it again, so that the configuration files may not conflict, but I don’t know how to start.
These are the two API teaching URLs I practiced
http://www.expertphp.in/article/user-login-and-registration-using-nodejs-and-mysql-with-example
https://www.footmark.info/programming-language/nodejs/nodejs-restful-webapi-mysql/
index.js
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var authenticateController = require("./controllers/authenticate-controller");
var registerController = require("./controllers/register-controller");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post("/api/register", registerController.register);
app.post("/api/authenticate", authenticateController.authenticate);
app.listen(3000);
app.js
var bodyparser = require("body-parser");
var express = require("express");
var conf = require("./conf");
var functions = require("./functions");
var user = require("./routes/user");
var app = express();
req.body
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
//app.use(functions.passwdCrypto);
app.use("/user", user);
app.listen(conf.port, function() {
console.log("app listening on port " + conf.port + "!");
});
authenticate-controller.js
var connection = require('./../conf');
module.exports.authenticate=function(req,res){
var email=req.body.email;
var password=req.body.password;
connection.query('SELECT * FROM user WHERE email = ?',[email], function (error, results, fields) {
if (error) {
res.json({
status:false,
message:'there are some error with query'
})
}else{
if(results.length >0){
if(password==results[0].password){
res.json({
status:true,
message:'successfully authenticated'
})
}else{
res.json({
status:false,
message:"Email and password does not match"
});
}
}
else{
res.json({
status:false,
message:"Email does not exits"
});
}
}
});
}
register-controller.js
var connection = require('../conf');
module.exports.register=function(req,res){
var today = new Date();
var user={
"name":req.body.name,
"email":req.body.email,
"password":req.body.password,
"created_at":today,
"updated_at":today
}
connection.query('INSERT INTO user SET ?',user, function (error, results, fields) {
if (error) {
res.json({
status:false,
message:'there are some error with query'
})
}else{
res.json({
status:true,
data:results,
message:'user registered sucessfully'
})
}
});
}
user.js(models)
var mysql = require("mysql");
var conf = require("../conf");
var connection = mysql.createConnection(conf.db);
var sql = "";
module.exports = {
items: function(req, callback) {
sql = "SELECT * FROM user";
return connection.query(sql, callback);
},
item: function(req, callback) {
sql = mysql.format("SELECT * FROM user WHERE userId = ?", [req.params.id]);
return connection.query(sql, callback);
},
add: function(req, callback) {
sql = mysql.format("INSERT INTO user SET ?", req.body);
return connection.query(sql, callback);
},
delete: function(req, callback) {
sql = mysql.format("DELETE FROM user WHERE userId = ?", [req.params.id]);
return connection.query(sql, callback);
},
put: function(req, callback) {
connection.beginTransaction(function(err) {
if (err) throw err;
sql = mysql.format("DELETE FROM user WHERE userId = ?", [req.params.id]);
connection.query(sql, function(err, results, fields) {
if (results.affectedRows) {
req.body.id = req.params.id;
sql = mysql.format("INSERT INTO user SET ?", req.body);
connection.query(sql, function(err, results, fields) {
if (err) {
connection.rollback(function() {
callback(err, 400);
});
} else {
connection.commit(function(err) {
if (err) callback(err, 400);
callback(err, 200);
});
}
});
} else {
callback(err, 410);
}
});
});
},
patch: function(req, callback) {
sql = mysql.format("UPDATE user SET ? WHERE userId = ?", [req.body, req.params.id]);
return connection.query(sql, callback);
}
};
user.js(routes)
var express = require("express");
var user = require("../models/user");
var router = express.Router();
router
.route("/")
.get(function(req, res) {
user.items(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (!results.length) {
res.sendStatus(404);
return;
}
res.json(results);
});
})
.post(function(req, res) {
user.add(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
res.status(201).json(results.insertId);
});
});
router
.route("/:id")
.get(function(req, res) {
user.item(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (!results.length) {
res.sendStatus(404);
return;
}
res.json(results);
});
})
.delete(function(req, res) {
user.delete(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (!results.affectedRows) {
res.sendStatus(410);
return;
}
res.sendStatus(204);
});
})
.put(function(req, res) {
user.put(req, function(err, results) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (results === 410) {
res.sendStatus(410);
return;
}
user.item(req, function(err, results, fields) {
res.json(results);
});
});
})
.patch(function(req, res) {
user.patch(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (!results.affectedRows) {
res.sendStatus(410);
return;
}
req.body.id = req.params.id;
res.json([req.body]);
});
});
module.exports = router;
conf.js
var mysql = require("mysql");
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "1234",
database: "farmbot",
});
connection.connect(function(err) {
if (!err) {
console.log("Database is connected");
} else {
console.log("Error while connecting with database");
}
});
module.exports = connection;
/*If I comment out the code below, I can execute the login / register API*/
/*Without commenting out, can only perform CRUD on the database*/
module.exports = {
db: {
host: "localhost",
user: "root",
password: "1234",
database: "farmbot"
},
port: 3000
};
You will have to refactor them properly. You will need only once file to begin with. Why using it twice?
Refactor them in one file instead of listening to them on different ports. Once done, you can show the code to us so that we can fix it further if there's an issue.
Start from index.js and merge app.js with it but a bit carefully. I think doing it by yourself you will learn much from it.

How to connect to mysql properly in nodejs?

what i trying to do here is query to mysql database, but when i execute my query, it just loading forever, no error untill it timed out, how to solve this? below is my db.js code :
Db.js :
var mysql = require("mysql");
var settings = require("../settings");
exports.executeSql = function (sql, callback) {
var conn = new mysql.createConnection(settings.dbConfig);
conn.connect(function(err){
if(err){
console.log(err + "1");
return;
}
console.log(conn.log + "2");
})
};
and here is my bassCtrl.js :
var db = require("../core/db");
var httpMsgs = require("../core/httpMsgs");
exports.get_user = function(req, resp) {
db.executeSql("select * from mst_user", function(data, err) {
console.log("in controller");
if (err) {
httpMsgs.show500(req, resp, err);
} else {
httpMsgs.sendJson(req, resp, data);
};
});
};
and here is my routes.js
var express = require('express');
var bassCtrl = require("../controllers/bassCtrl");
var httpMsgs = require("../core/httpMsgs");
var jwt = require('jsonwebtoken');
module.exports = function(app, express) {
var router = express();
router.route('/get_user').get(bassCtrl.get_user);
return router;
};
below is my HttpMsgs.js :
var settings = require("../settings");
exports.show500 = function(req, resp, err) {
if (settings.httpMsgsFormat === 'HTML') {
resp.writeHead(500, "Internal Error occuared", {"Content-Type":"text/html"});
resp.write("<html><head><title>500</title></head><body>500: Internal Error. Details: " + err + "</body></html>");
} else {
resp.writeHead(500, "Internal Error occuared", {"Content-Type":"application/json"});
resp.write(JSON.stringify({ data: "Error occurred: " + err }));
}
resp.end();
}
exports.sendJson = function(req, resp, data) {
resp.writeHead(200, {"Content-Type":"application/json"});
if (data) {
resp.write(JSON.stringify(data));
}
resp.end();
}
exports.show405 = function(req, resp) {
if (settings.httpMsgsFormat === 'HTML') {
resp.writeHead(405, "Method not supported", {"Content-Type":"text/html"});
resp.write("<html><head><title>405</title></head><body>405: Method not supported.</body></html>");
} else {
resp.writeHead(405, "Method not supported", {"Content-Type":"application/json"});
resp.write(JSON.stringify({ data: "Method not supported"}));
}
resp.end();
}
exports.show413 = function(req, resp) {
if (settings.httpMsgsFormat === 'HTML') {
resp.writeHead(404, "Resource not found", {"Content-Type":"text/html"});
resp.write("<html><head><title>413</title></head><body>404: Resource not found.</body></html>");
} else {
resp.writeHead(404, "Resource not found", {"Content-Type":"application/json"});
resp.write(JSON.stringify({ data: "Resource not found"}));
}
resp.end();
}
exports.show413 = function(req, resp) {
if (settings.httpMsgsFormat === 'HTML') {
resp.writeHead(413, "Request Entity Too Large", {"Content-Type":"text/html"});
resp.write("<html><head><title>413</title></head><body>413: Request Entity Too Large.</body></html>");
} else {
resp.writeHead(413, "Request Entity Too Large", {"Content-Type":"application/json"});
resp.write(JSON.stringify({ data: "Request Entity Too Large"}));
}
resp.end();
}
exports.send200 = function(req, resp) {
resp.writeHead(200, {"Content-Type":"application/json"});
resp.write(JSON.stringify(
{status: "success", code: 200}
));
resp.end();
}
exports.showHome = function(req, resp) {
if (settings.httpMsgsFormat === 'HTML') {
resp.writeHead(200, {"Content-Type":"text/html"});
resp.write("<html><head><title>200</title></head><body>Your server connected dude ! :)</body></html>");
} else {
resp.writeHead(200, {"Content-Type":"application/json"});
resp.write(JSON.stringify(
{status: "Your server connected dude ! :)"}
));
}
resp.end();
}
and here is my settings.js :
exports.dbConfig = {
user: "root",
password: "",
host: "localhost",
database: "zouk"
};
exports.httpMsgsFormat = "json";
when i trigger localhost:5000/get_user, it just loading till it timed out, and my console.log print this line console.log(connection.log + "2"); with undefined as the value. is there something i missing?
wait a minute, why my question rated minus?
You didn't execute your query in Db.js file, and your code don't call the callback too, that's why it run until timeout.
var connection = mysql.createConnection({
host : ***,
user : ***,
password : ***,
database : ***,
});
connection.connect();
connection.query(sql, function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
//your callback go here.
// callback(rows);//pass whatever you need in.
});
connection.end();
Plus, your controller have no require for httpMsgs. I think it should have.

NodeJS error when rendering page:Cast to ObjectId failed for value "styles.css" at path "_id"

The error prevents my webpage from being rendered. As mentioned in the title, the error lies in styles.css, when I take this file out, I do not get any errors.
styles.css is included in a separate headers.ejs file which is added in all pages, but there is only one route for which the error is shown(/cats/new). I put up some some logs around my routes and it seems when I enter /cats/new/, I am automatically redirected to a new route (get /cats/:id). I am wondering if this is the cause of the error?
I have attached my routes and the full error message below:
routes:
var express = require('express');
var router = express.Router();
var User = require('../models/user.js');
var Cat = require('../models/cat.js');
var Comment = require('../models/comment.js');
//middleware
function isAuthenticated(req,res,next) {
req.isAuthenticated() ? next() : res.redirect('/login');
}
router.get("/", function(req,res) {
res.redirect("cats");
});
router.get('/cats', function(req,res) {
Cat.find({}, function(err, cats) {
if (err) {
console.log(err);
} else {
res.render('cats', {cats: cats});
}
});
});
router.get('/cats/new', isAuthenticated, function(req,res) {
console.log('went to /cats/new');
res.render('new', {user: req.user});
});
router.post('/cats', isAuthenticated, function(req,res) {
console.log('went to post /cats');
var name = req.body.name;
var image = req.body.url;
var owner = req.user.username
var description = req.body.description;
cat = new Cat({
name: name,
image: image,
owner: owner,
description: description
});
cat.save();
User.findById(req.user._id, function(err, user) {
if (err) {
console.log(err);
} else {
user.cats.push(cat);
user.save();
}
})
res.redirect('cats');
});
router.get('/cats/:id', function(req,res) {
var id = req.params.id;
Cat.findById(id).populate('comments').exec(function(err, cat) {
if (err) {
console.log('entering get /cats/:id');
console.log(err);
} else {
console.log('no errror yet');
console.log(cat.comments);
res.render('show', {cat:cat});
}
});
});
router.post('/cats/:id', isAuthenticated, function(req,res) {
console.log(isAuthenticated);
var id = req.params.id;
Cat.findById(id, function(err, cat) {
console.log('findById running');
if (err) {
console.log(err);
console.log('err finding cat');
res.redirect('/cats');
} else {
console.log('before Comment.create');
Comment.create(req.body.comment, function(err, comment) {
console.log('after Comment.create');
if (err) {
console.log(err);
} else {
console.log('right after 2nd else');
comment.author.id = req.user._id;
console.log(req.user._id);
console.log(req.user.username);
comment.author.username = req.user.username;
comment.cat = id;
comment.save();
console.log('after saving comment');
cat.comments.push(comment);
cat.save();
console.log('saved cat');
User.findById(req.user._id, function(err, user) {
if (err) {
console.log(err);
} else {
user.comments.push(comment);
user.save();
console.log('saved user');
}
});
console.log(comment);
res.redirect("/cats/" + cat._id);
}
});
}
});
});
router.get('/cats/:id/edit', function(req,res) {
var id = req.params.id;
Cat.findById(id, function(err, cat) {
if (err) {
console.log(err);
} else {
res.render('edit.ejs', {cat:cat});
}
});
});
router.put('/cats/:id', function(req,res) {
console.log('beginning /cat/:id');
Cat.findByIdAndUpdate(
req.params.id, req.body.cat, function(err, updatedCat) {
if (err) {
console.log(err);
} else {
console.log('------------ req.body.cat');
console.log(req.body.cat);
console.log('------------ updated cat');
console.log('updated cat');
res.redirect('/cat/' + req.params.id);
console.log('not redirecting?');
}
});
router.delete('/cats/:id',isAuthenticated, function(req,res) {
var id = req.params.id;
console.log('YOU ARE TRYING TO DESTROY A CAT!');
Cat.findByIdAndRemove(id, function(err) {
if (err) {
console.log(err);
res.redirect('/user');
} else {
res.redirect('/user');
}
});
})
});
module.exports = router;
Error:
entering get /cats/:id
{ [CastError: Cast to ObjectId failed for value "styles.css" at path "_id"]
message: 'Cast to ObjectId failed for value "styles.css" at path "_id"',
name: 'CastError',
kind: 'ObjectId',
value: 'styles.css',
path: '_id',
reason: undefined }
It seems you’re including styles.css using a relative path in your template.
So when you navigate to /cats/:id, it tries to load /cats/styles.css.
In order to avoid that, you have to use an absolute path (e.g.: /styles.css or /public/styles.css – I’d recommend serving static files from a dedicated base path).
Go to
<head>
and change
<link rel="stylesheet" href="style.css">
to
<link rel="stylesheet" href="/style.css">

'hash' String is not a function

Could somebody please tell me why I can't seem to get past the login page here?
app.configure(function() {
this.engine('ejs', require('ejs-locals'));
this.set('views', path.join(__dirname, 'views'));
this.set('view engine', 'ejs');
this.use(express.static(path.join(__dirname, '/public')));
this.use(express.static(path.join(__dirname, '/views/login')));
this.use(express.static(path.join(__dirname, '/views/el')));
// Allow parsing cookies from request headers
this.use(express.cookieParser());
this.use(express.session({
"secret": sessionSecret,
"store": sessionStore
}));
// Allow parsing form data
this.use(express.bodyParser());
});
app.configure('development', function() {
this.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
app.configure('production', function() {
this.use(express.errorHandler());
});
function authenticate(name, password, fn) {
if (!module.parent) console.log('authenticating %s:%s', name, password);
User.findOne({
username: name
},
function(err, user) {
if (user) {
if (err) return fn(new Error('cannot find user'));
hash(password, user.salt, function(err, hash) {
if (err) return fn(err);
if (hash == user.hash) return fn(null, user);
fn(new Error('invalid password'));
});
} else {
return fn(new Error('cannot find user'));
}
});
}
function requiredAuthentication(req, res, next) {
if (req.session.user) {
next();
} else {
req.session.error = 'Access denied!';
res.redirect('/login');
}
}
function userExist(req, res, next) {
User.count({
username: req.body.username
}, function(err, count) {
if (count === 0) {
next();
} else {
req.session.error = "User Exists"
res.redirect("/signup");
}
});
}
//Routes
app.get("/", function(req, res) {
if (req.session.user) {
res.send("Welcome " + req.session.user.username + "<br>" + "<a href='/logout'>logout</a>");
} else {
res.render("./login/login");
}
});
app.get("/signup", function(req, res) {
if (req.session.user) {
res.redirect("/");
} else {
res.render("./login/Signup");
}
});
app.post("/signup", userExist, function(req, res) {
var password = req.body.password;
var username = req.body.username;
hash(pass, function(err, salt, hash) {
if (err) throw err;
var user = new User({
username: username,
salt: salt,
hash: hash,
}).save(function(err, newUser) {
if (err) throw err;
authenticate(newUser.username, password, function(err, user) {
if (user) {
req.session.regenerate(function() {
req.session.user = user;
req.session.success = 'Authenticated as ' + user.username + ' click to logout. ' + ' You may now access /.';
res.redirect('/');
});
}
});
});
});
});
app.get("/login", function(req, res) {
res.render("./login/login");
});
app.post("/login", function(req, res) {
authenticate(req.body.username, req.body.password, function(err, user) {
if (user) {
req.session.regenerate(function() {
req.session.user = user;
req.session.success = 'Authenticated as ' + user.username + ' click to logout. ' + ' You may now access /restricted.';
res.redirect('/');
});
} else {
req.session.error = 'Authentication failed, please check your ' + ' username and password.';
res.redirect('/login');
}
});
});
app.get('/logout', function(req, res) {
req.session.destroy(function() {
res.redirect('/');
});
});
app.get('/profile', requiredAuthentication, function(req, res) {
res.send('Profile page of ' + req.session.user.username + '<br>' + ' click to logout');
});
When I compile my server.js file with node and go to localhost, the login page appears. When I enter the username and password that I had already inserted in my Mongo DB, I get this message:
Unable to connect
Firefox can't establish a connection to the server at localhost.
The site could be temporarily unavailable or too busy. Try again in a few moments.
If you are unable to load any pages, check your computer's network connection.
If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the Web.
With my Node prompt displaying the following:
/home/ghanem/server/www/server.js:210
hash(password, user.salt, function (err, hash) {
^ TypeError: string is not a function
at /home/ghanem/server/www/server.js:210:12
at /home/ghanem/server/www/node_modules/mongoose/lib/query.js:1170:16
at /home/ghanem/server/www/node_modules/mongoose/node_modules/kareem/index.js:103:16
at process._tickCallback (node.js:415:13)

Categories